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.

This entry was posted in Powershell Basics. Bookmark the permalink.

One Response to Modifying text

  1. HI Richard,

    You can also say:

    ${C:\Test\test.txt} = ${C:\Test\test.txt}.Replace(“I want”, “I need”)

    (An unfortunate limitation of this syntax is that the paths are literals only…)

    Cheers,
    Chris

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s