I want to add content into the middle of a text file in Powershell. I'm searching for a specific pattern, then adding the content after it. Note this is in the middle of the file.
What I have currently is:
(Get-Content ( $fileName )) | Foreach-Object { if($_ -match "pattern") { #Add Lines after the selected pattern $_ += "`nText To Add" } } } | Set-Content( $fileName )
However, this doesn't work. I'm assuming because $_ is immutable, or because the += operator doesn't modify it correctly?
What's the way to append text to $_ that will be reflected in the following Set-Content call?
Description. The Add-Content cmdlet appends content to a specified item or file. You can specify the content by typing the content in the command or by specifying an object that contains the content.
When you want to read the entire contents of a text file, the easiest way is to use the built-in Get-Content function. When you execute this command, the contents of this file will be displayed in your command prompt or the PowerShell ISE screen, depending on where you execute it.
Just output the extra text e.g.
(Get-Content $fileName) | Foreach-Object { $_ # send the current line to output if ($_ -match "pattern") { #Add Lines after the selected pattern "Text To Add" } } | Set-Content $fileName
You may not need the extra ``n` since PowerShell will line terminate each string for you.
How about this:
(gc $fileName) -replace "pattern", "$&`nText To Add" | sc $fileName
I think that is fairly straight-forward. The only non-obvious thing is the "$&", which refers to what was matched by "pattern". More info: http://www.regular-expressions.info/powershell.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With