Table of Contents
💡 TL;DR
To replace String in multiple files, use
Get-ChildItemto get all the required files and iterate over the files usingForEach-Object. In each iteration, read the file content usingGet-Contentcmdlet, usereplace()method to replace text andSet-Contentto save the content in the files.
Here is simple example:Let’s say, you want to replace all the spaces to underscore in all txt files under folder
C:\Users\Arpit\Desktop\powershell.
12345678 $DirPath = "C:\Users\Arpit\Desktop\powershell"get-childitem $DirPath -recurse -include *.txt |ForEach-Object {(Get-Content $_).replace(" ","_") |Set-Content $_}
Replace String in multiple Files in PowerShell
There are 2 different ways to replace String in multiple Files in PowerShell.
Using replace() method with Get-ChildItem
Here are the steps to replace String in multiple files using replace() method.
- Store the file path in variable
$DirPath - Use
Get-ChildItemcmdlet to get all the required files in$DirPath. You can use-includeoption to select only particular file extension. - Use
ForEach-Objectto iterate over each item. - In each iteration, use
Get-Contentcmdlet to read content of the file.Get-Contentreads the content of the item at particular location specified by the path. - Use
replace()method to replace old text with new text.replace()method returns new String and replaces each occurence of old text with new text. - Lastly, use
Set-Contentcmdlet to replace the content of the all the files.
|
1 2 3 4 5 6 7 8 |
$DirPath = "C:\Users\Arpit\Desktop\powershell" get-childitem $DirPath -recurse -include *.txt | ForEach-Object { (Get-Content $_).replace(" ","_") | Set-Content $_ } |
Further reading:
Using replace operator with Get-ChildItem
Most of the steps will be similar to previous method. We will use replace operator instread of replace() method to replace content in multiple files.
Here are the steps to replace String in multiple files using replace operator.
- Store the file path in variable
$DirPath - Use
Get-ChildItemcmdlet to get all the required files in$DirPath. You can use -include option to select only particular file extension. - Use
ForEach-Objectto iterate over each item. - In each iteration, use
Get-Contentcmdlet to read content of the file.Get-Contentreads the content of the item at particular location specified by the path. - Use
replaceoperator to replace old text with new text.replaceoperator returns new String and replaces each occurence of old text with new text. - Lastly, use
Set-Contentcmdlet to replace the content of the all the files.
|
1 2 3 4 5 6 7 8 |
$DirPath = "C:\Users\Arpit\Desktop\powershell" get-childitem $DirPath -recurse -include *.txt | ForEach-Object { (Get-Content $_) -replace " ","_" | Set-Content $_ } |
That’s all about how to replace String in multiple files in PowerShell.