Aaron Wurthmann
Aaron Wurthmann

Reputation: 6765

Perpend X Number of Lines in a File with PowerShell

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 beginning or the end

Upvotes: 1

Views: 199

Answers (2)

xcud
xcud

Reputation: 14732

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

Upvotes: 2

Roman Kuzmin
Roman Kuzmin

Reputation: 42063

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.

Upvotes: 0

Related Questions