2

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.

0

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.