Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert Content into Text File in Powershell

Tags:

powershell

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?

like image 880
Jeff Avatar asked Dec 09 '09 17:12

Jeff


People also ask

What is add-content in PowerShell?

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.

How do I get the content of a text file in PowerShell?

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.


2 Answers

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.

like image 188
Keith Hill Avatar answered Sep 22 '22 11:09

Keith Hill


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

like image 28
dan-gph Avatar answered Sep 21 '22 11:09

dan-gph