Encore
Encore

Reputation: 91

Replace a string in a file, and have some feedback about what was done

I would like to replace a string in a file, and then know if something was actually replaced. I have many files to parse, and I know only very few will have to be corrected. So I would like to write the file out only if a changed occurs. Also I would like to be able to trace the changes in a log...

For example, I've been trying this :

(Get-Content $item.Fullname) | Foreach-Object {$_ -replace $old, $new} |
  Out-File $item.Fullname

But using I can't tell if any changes were done or not...

Do you have any solution?

Upvotes: 2

Views: 70

Answers (2)

briantist
briantist

Reputation: 47792

Do it in multiple steps:

$content = [System.IO.File]::ReadAllText($item.FullName)
$changedContent = $content -replace $old,$new

if ($content -ne $changedContent) {
    # A change was made
    # log here
    $changedContent | Set-Content $item.FullName
} else {
    # No change
}

Upvotes: 2

David
David

Reputation: 6571

Use select-string like grep to detect the string and log a message, then use get- and set-content to replace the string:

$item = 'myfile.txt'
$searchstr = "searchstring"
$replacestr = "replacestring"

if (select-string -path $item -pattern $searchstr) {
    write-output "found a match for: $searchstr in file: $item"
    $oldtext = get-content $item
    $newtext = $oldtext.replace($searchstr, $replacestr)
    set-content -path $item -value $newtext
}

Upvotes: 1

Related Questions