To search and replace within a single line of text use the -replace operator
PS C:\> "abcdef" -replace "dEf","xyz"
To perform multiple replaces, these can be chained:
PS C:\> "abcdef" -replace "dEf","xyz" -replace "cx","-"
Search and replace across all the lines in a text file:
$filePath = "c:\demo\source.html"
$newLine = "`r`n"
$search1 = '</head>'
$search2 = '<body>'
$searchLines = $search1 += $newLine += $search2
$new1 = '</head><body>'
$new2 = '<p class="demo">Welcome to the machine '
$newLines = $new1 += $newLine += $new2
$allTheText = [System.Io.File]::ReadAllText($filePath)
$result = $allTheText.Replace($searchLines,$newLines)
"$result" > "c:\demo\result.html"
The file is read using the .Net ::ReadAllText method rather than Get-Content because we want to read in the entire file as a single long text string rather than a collection of strings, note also the use of 'single quotes' around the search strings to ensure that all punctuation is ignored by PowerShell.
“I can make a General in five minutes but a good horse is hard to replace” ~ Abraham Lincoln
Replace-FileString.ps1 - Find and Replace across multiple files (Bill Stewart)
Get-Content - Get content from item
© Copyright SS64.com 1999-2013
Some rights reserved