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:
Thank you. I've been pulling my hair about prepending something
thank you!
Years later still helpful. Thanks. .
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
Thank you for writing this up!
Post a Comment