Windows 使用PowerShell的文件中的垂直X行数

Windows 使用PowerShell的文件中的垂直X行数,windows,powershell,comments,Windows,Powershell,Comments,我被一个文本文件的问题困住了。该文件只是一个带有一些已添加日期的纯文本文件,换句话说,是一个简单的日志文件。我的问题是“我需要注释掉许多行,这些行作为参数传递”。我挂断的部分是实际注释X行数部分(假设添加了a)。我可以用搜索字符串读写文件、读行和写行,但我似乎不知道如何编辑X行数,而不去管其他行 PS 实际上,行是在文件末尾还是在文件开头并不重要,尽管了解如何添加到开头或结尾的方法会很好如果我正确,那么此模式应该适合您: (Get-Content my.log) | .{ begin{

我被一个文本文件的问题困住了。该文件只是一个带有一些已添加日期的纯文本文件,换句话说,是一个简单的日志文件。我的问题是“我需要注释掉许多行,这些行作为参数传递”。我挂断的部分是实际注释X行数部分(假设添加了a)。我可以用搜索字符串读写文件、读行和写行,但我似乎不知道如何编辑X行数,而不去管其他行

PS
实际上,行是在文件末尾还是在文件开头并不重要,尽管了解如何添加到开头或结尾的方法会很好

如果我正确,那么此模式应该适合您:

(Get-Content my.log) | .{
    begin{
        # add some lines to the start
        "add this to the start"
        "and this, too"
    }
    process{
        # comment out lines that match some condition
        # in this demo: a line contains 'foo'
        # in your case: apply your logic: line counter, search string, etc.
        if ($_ -match 'foo') {
            # match: comment out it
            "#$_"
        }
        else {
            # no match: keep it as it is
            $_
        }
    }
    end {
        # add some lines to the end
        "add this to the end"
        "and this, too"
    }
} |
Set-Content my.log
然后是日志文件:

bar
foo
bar
foo
转化为:

add this to the start
and this, too
bar
#foo
bar
#foo
add this to the end
and this, too
注意:对于非常大的文件,请使用类似但略有不同的模式:

Get-Content my.log | .{
    # same code
    ...
} |
Set-Content my-new.log

然后将
my new.log
重命名为
my.log
。如果您仍要写入新文件,那么首先使用第二种更有效的模式。

我一直在考虑对尚未使用计数器的注释的每行进行foreach,当该计数器被点击时,停止/退出;但是听起来很混乱,必须有更好的方法。谢谢你的回答。但是问题是所有线条看起来都一样$日期$user$计算机,因此使用搜索和替换不会起作用。请注意,对于较大的文件,您可能希望缓存
Get Content
的结果,以避免读取两次。特别重要的是,如果你不是从一个快速的本地驱动器读取。
gc .\foo.txt | select -First 3 | %{ "#{0}" -f $_ }
gc .\foo.txt | select -Skip 3