PowerShell: How to Replace Specific Text in Multiple Files


You can use the following syntax in PowerShell to replace specific text in multiple files:

Get-ChildItem -File -Recurse | ForEach-Object {
    (Get-Content $_) -replace "Mavs","Mavericks" | Set-Content $_.fullname
}

This particular example will replace the text “Mavs” with “Mavericks” in every file in the current directory.

Here is what the various commands do:

  • Get-ChildItem -File -Recurse: Retrieve all files recursively from current directory
  • ForEach-Object: Specifies an action to perform on each file
  • Get-Content $_: Retrieve the contents of the current file
  • -replace: Specifies an old pattern to replace with a new pattern
  • Set-Content $_.fullname: Update the contents of the current file after the replacement has been made

The following example shows how to use this syntax in practice.

Example: How to Replace Specific Text in Multiple Files in PowerShell

Suppose that our current directory contains the following three text files:

  • teams1.txt
  • teams2.txt
  • teams3.txt

We can use the Get-Content cmdlet to view the contents of each of these files:

Each of the files contain the names of various basketball teams.

Suppose that we would like to replace the team name “Mavs” with “Mavericks” in each file.

We can use the following syntax to do so:

Get-ChildItem -File -Recurse | ForEach-Object {
    (Get-Content $_) -replace "Mavs","Mavericks" | Set-Content $_.fullname
}

The following screenshot shows how to use this syntax in practice:

PowerShell replace text in multiple files

Notice that when we use the Get-Content cmdlet to view the updated contents of each file we can see that the pattern “Mavs” has been replaced with “Mavericks” in each file that contained the pattern.

Feel free to replace “Mavs” with any other pattern that you would like to search for in your own files.

Note: You can find the complete documentation for the -replace operator in PowerShell here.

Related Tutorials

The following tutorials explain how to perform other common tasks in PowerShell:

PowerShell: How to Replace Multiple Strings in File
PowerShell: How to Check if String Exists in List of Strings
PowerShell: How to Replace Special Characters in String
PowerShell: How to Replace Text in String

Leave a Reply