Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Search and replace with PowerShell

I'm using the below PowerShell script to search and replace, which works fine.

$files = Get-ChildItem 'E:\replacetest' -Include "*.txt" -Recurse | ? {Test-Path $_.FullName -PathType Leaf}

foreach($file in $files)
{
    $content = Get-Content $file.FullName | Out-String
    $content| Foreach-Object{$_ -replace 'hello' , 'hellonew'`
                                -replace 'hola' , 'hellonew' } | Out-File $file.FullName -Encoding utf8
}

The issue is the script also modifies the files which does not have the matching text in it. How we ignore the files that do not have the matching text?

like image 397
user2628187 Avatar asked Feb 11 '26 13:02

user2628187


1 Answers

You can use match to see if the content is actually changed. Since you were always writing using out-file the file would be modified.

$files = Get-ChildItem 'E:\replacetest' -Include "*.txt" -Recurse | Where-Object {Test-Path $_.FullName -PathType Leaf}

foreach( $file in $files ) { 
    $content = Get-Content $file.FullName | Out-String
    if ( $content -match ' hello | hola ' ) {
        $content -replace ' hello ' , ' hellonew ' `
                 -replace ' hola ' , ' hellonew ' | Out-File $file.FullName -Encoding utf8
        Write-Host "Replaced text in file $($file.FullName)"
    }    
}
like image 89
Shawn Esterman Avatar answered Feb 14 '26 03:02

Shawn Esterman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!