Arvind Naik
Arvind Naik

Reputation: 41

How can I replace every occurrence of a String in a file with PowerShell?

This question is similar to earlier question How can I replace every occurence of a String in a file with PowerShell?" except my challenge is to replace the text is multiple files. I tried using the solution in earlier question and used a command similar like below.

(Get-Content .\*.txt).replace("old text", "new text") | Set-Content .\*.txt

It seem to work but the each file size has increased drastically to the total of files in the directory. Although when I open any file it seems to look normal.

Anyone has ideas how to fix it. My litmus test would be I should revert my text changes and file sizes shouldn't change at all.

Upvotes: 2

Views: 456

Answers (1)

mklement0
mklement0

Reputation: 440637

You must process the files one at a time:

Get-Item *.txt | 
  ForEach-Object { 
     $f = $_.FullName; (Get-Content $f).replace("old text", "new text") | Set-Content $f 
  }

Note that this will fail with completely empty (zero-byte) files.

Also, irrespective of what the encoding of the input files was, the output files will have Default encoding, according to the system's legacy code page (typically, a single-byte, extended-ASCII encoding).


As for what you tried:

  • (Get-Content .*.txt) sends the lines from all *.txt files as a single array of lines through the pipeline.

  • Set-Content *.txt then sends that one array (with replacements made) as a whole to every *.txt file in the current directory.

Upvotes: 4

Related Questions