PowerShell for Windows Admins

Jan 31 2015   7:54AM GMT

Modifying text

Richard Siddaway Richard Siddaway Profile: Richard Siddaway

Tags:
Powershell

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.

 Comment on this Post

 
There was an error processing your information. Please try again later.
Thanks. We'll let you know when a new response is added.
Send me notifications when other members comment.

Forgot Password

No problem! Submit your e-mail address below. We'll send you an e-mail containing your password.

Your password has been sent to:

Share this item with your network: