Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Powershell to replace text in multiple files stored in many folders

I want to replace a text in multiple files and folders. The folder name changes, but the filename is always config.xml.

$fileName = Get-ChildItem "C:\config\app*\config.xml" -Recurse
(Get-Content $fileName) -replace 'this', 'that' | Set-Content $fileName

When I run the above script it works, but it writes the whole text in config.xml about 20 times. What's wrong?

like image 814
aston_zh Avatar asked Feb 04 '14 17:02

aston_zh


People also ask

How do I replace text in multiple files?

Remove all the files you don't want to edit by selecting them and pressing DEL, then right-click the remaining files and choose Open all. Now go to Search > Replace or press CTRL+H, which will launch the Replace menu. Here you'll find an option to Replace All in All Opened Documents.

How do you replace text in PowerShell?

Using the Replace() Method The replace() method has two arguments; the string to find and the string to replace the found text with. As you can see below, PowerShell is finding the string hello and replacing that string with the string hi . The method then returns the final result which is hi, world .

How do I replace multiple characters in a string in PowerShell?

You can replace multiple characters in a string using PowerShell replace() method or PowerShell replace operator. If you are using the PowerShell replace() method, you can chain replace() method as many times to replace the multiple characters in the PowerShell string.

How do I change multiple file extensions in PowerShell?

Change file extensions with PowerShell You can also use the Rename-Item to change file extensions. If you want to change the extensions of multiple files at once, use the Rename-Item cmdlet with the Get-ChildItem cmdlet.


1 Answers

$filename is a collection of System.IO.FileInfo objects. You have to loop to get the content for each file : this should do what you want :

$filename | %{
    (gc $_) -replace "THIS","THAT" |Set-Content $_.fullname
}
like image 182
Loïc MICHEL Avatar answered Oct 16 '22 01:10

Loïc MICHEL