使用PowerShell在文件中包含X行数

时间:2010-11-16 05:29:33

标签: windows powershell comments

我遇到了一个我正在处理文本文件的问题。该文件只是一个平面文本文件,其中添加了一些日期,换句话说就是一个简单的日志文件。我的问题是“我需要注释掉一些行,这个数字作为一个参数传递”。我所挂断的部分是实际注释掉X行数部分(假设添加了#)。我可以读取和写入文件,读取行和用搜索字符串写行,但我似乎无法弄清楚如何编辑X行数并留下其他行。

PS 实际上,如果这些行位于文件的末尾或者开头是没关系的,尽管理解如何添加到开头或结尾的方法会很好

2 个答案:

答案 0 :(得分:2)

gc .\foo.txt | select -First 3 | %{ "#{0}" -f $_ }
gc .\foo.txt | select -Skip 3

答案 1 :(得分:0)

如果我做对了,那么这种模式应该适合你:

(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。如果你打算写一个新文件,那么首先使用第二个更有效的模式。