logo-powershellChange a string in a text file

This script lists all files in a specific folder and replace a string within these files

The following cmdlets are used in the script :

  • Get-childitem : list the files to update
  • Get-content : open and read the files
  • Set-content : write the changes to file

Script :

$filelist = Get-ChildItem "C:\temp\MyFolder"
foreach ($file in $filelist){
$new = (Get-Content $file.fullname) -replace "String to replace", "New String"
Set-Content $file.fullname $new
}

Reference

Replace method

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")
abcxyz

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 

Rename file extensions from .log to .txt

PS C:\> dir *.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)
Change a string in a text file

Leave a Reply

Your email address will not be published.