Friday, August 7, 2009

Powershell script for prepending and appending text

I recently had the need to go through a text file and prepend a string to every line, and while that's ok for a couple of lines it doesn't work for a file with hundreds and thousands of lines. So here's the powershell command to do that:


get-content file.txt | foreach-object {add-content output.txt "text_to_add $_"}


This goes through every line in file.txt, adds "text_to_add" followed by a space and then whatever was on the original line (which is put in by the $_ ) and then writes that out to output.txt.


If you wanted to append to the end of every line it would be:


get-content file.txt | foreach-object {add-content output.txt "$_ text_to_add "}


If you wanted search for and replace only specific lines you'd write a function to do so which a good example of searching through a text file I've found here.


5 comments:

Sam said...

Thank you. I've been pulling my hair about prepending something

Anonymous said...

thank you!

Unknown said...

Years later still helpful. Thanks. .

Unknown said...

Your code worked well... but slowly for large files and lots of them.
To speed it up I used this, which bypasses the slow file I/O introduced by the Add-Conent commandlet.
Increased the speed ~27x (on my system)


$prependVar = "some text"
$lines = get-content file.txt
$newlines = $lines | ForEach-Object{ "$prependVar$_"}
$newlines | Out-File file.txt

Anonymous said...

Thank you for writing this up!