Monthly Archive

Categories

Modifying text

I needed to modify some text somewhere in a file. The file looks like this

##  start file
This is some text.

 

I want to change something.

 

But not this.
##  end file

 

I was playing around with various options.  The simplest I found was this:

£> $txt = Get-Content .\test.txt
£> $txt = $txt.Replace("I want", "I need")
£> Set-Content -Value $txt -Path C:\Test\test.txt
£> Get-Content .\test.txt
##  start file
This is some text.

 

I need to change something.

 

But not this.
##  end file

 

You could simplify to

£> $txt = (Get-Content .\test.txt).Replace("I want", "I need")
£> Set-Content -Value $txt -Path C:\Test\test.txt -PassThru

##  start file
This is some text.

 

I need to change something.

 

But not this.
##  end file

 

The passthru parameter displays the file contents you’ve set.

 

Or if you are a fan of convoluted one liners

£> Set-Content -Value ((Get-Content .\test.txt).Replace("I want", "I need")) -Path C:\Test\test.txt -PassThru
##  start file
This is some text.

 

I need to change something.

 

But not this.
##  end file

 

If you take this approach just make sure your text is uniquely identified otherwise you may change more than you thought.

Comments are closed.