Replace()

Replace characters within a string.

Syntax
      .Replace(strOldChar, strNewChar)

Key
   strOldChar  The characters to find.

   strNewChar  The characters to replace them with.

Examples

Replace characters in a string:

PS C:\> "abcdef" -replace "dEf","xyz"

Replace characters in a variable:

PS C:\> $demo = "abcdef"
PS C:\> $demo.replace("dEf","xyz")
bcxyz

Multiple replacements can be chained together in one command:

PS C:\> "abcdef" -replace "dEf","xyz"-replace "cx","-"
ab-yz

Search and Replace characters in a file:

PS C:\> $oldfile = "C:\demo\sourcetext.txt"
PS C:\> $newfile = "C:\demo\newfile.txt"

PS C:\> $text = (Get-Content -Path $oldfile -ReadCount 0) -join "`n"
PS C:\> $text -replace 'dEf', 'xyz' | Set-Content -Path $newfile

Search and Replace using a hash table:
 $text = 'Any old text string'
 
 $hash = @{}
 $hash.'old' = 'new'
 $hash.A = 'B'
 $hash.' ' = '_'
 Foreach ($key in $hash.Keys) {
    $text = $text.Replace($key, $hash.$key)
 }
 $text

This technique can also be used to replace common unicode characters.

Rename file extensions from .log to .txt

PS C:\> Get-ChildItem *.log | Rename-Item $_ -newname { $_.Name -replace '\.log','.txt' }

Using single quotes around the search strings will ensure that all punctuation is ignored by PowerShell.

An alternative method to read an entire file as a single long text string is the .Net ::ReadAllText method:
$allTheText = [System.Io.File]::ReadAllText($filePath)

More complex replacements can be done by combining -match or -replace with a regular expression.

“In order to be irreplaceable one must always be different” ~ Coco Chanel

Related PowerShell Cmdlets

Substring() - Return part of a longer string.
Insert - Insert(IntStartIndex, String_value).
Regular Expressions - Search and Replace within strings.
Set-Content - Find and Replace text within files.
PowerShell Methods
set-eol - Change the line endings (CR/LF) of a text file.
Replace-FileString.ps1 - Find and Replace across multiple files (Bill Stewart).


 
Copyright © 1999-2024 SS64.com
Some rights reserved