开发者

Perpend X Number of Lines in a File with PowerShell

开发者 https://www.devze.com 2023-01-25 01:48 出处:网络
I\'m stuck on a problem I\'m working on with a text file. The file is just a flat text file with some dates that have been added, in other words a simple log file. My problem is this \"I need to comme

I'm stuck on a problem I'm working on with a text file. The file is just a flat text file with some dates that have been added, in other words a simple log file. My problem is this "I need to comment out a number of lines, that number passed as a param". The part I'm hung up on is the actual commenting out X number of lines part (lets say a # is added). I can read and write files, read lines and write lines with a search string but what I can't seem to figure out is how to edit X number of lines and leave the other lines alone.

PS In actuality it doesn't matter if the lines are at the end of the file or the beginning, though it would be nice to understand the method on how to add to the beginni开发者_StackOverflow社区ng or the end


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


If I got it right then this pattern should work for you:

(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

Then the log file:

bar
foo
bar
foo

is transformed into:

add this to the start
and this, too
bar
#foo
bar
#foo
add this to the end
and this, too

Note: for very large files use a similar but slightly different pattern:

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

and then rename my-new.log to my.log. If you are about to write to a new file anyway then use the second more effective pattern in the first place.

0

精彩评论

暂无评论...
验证码 换一张
取 消