Quickly Replace Words in Text File

by Jun 6, 2013

In a previous tip we explained how you can convert a string array into one big string. That's a prerequisite for quickly searching and replacing instances of words in a text file.

This example takes windowsupdate.log and replaces all instances of "error" with "ALERT", saves the changes to a new file and opens it in your text editor:

$oldfile = "$env:windir\WindowsUpdate.log"
$newfile = "$env:temp\newfile.txt"

$text = (Get-Content -Path $oldfile -ReadCount 0) -join "`n"
$text -replace 'error', 'ALERT' | Set-Content -Path $newfile 
Invoke-Item -Path $newfile

In PowerShell 3.0, you can read the file content into a single string even faster by using the new switch parameter -Raw:

$text = Get-Content -Path $newfile -Raw

Twitter This Tip! ReTweet this Tip!