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.