PowerShell: How to Replace Multiple Strings in File


You can use the following basic syntax to replace multiple strings in a file using PowerShell:

(Get-Content c:\doc\data.txt).Replace('old1', 'new1').Replace('old2', 'new2') | Set-Content c:\doc\data.txt

This particular example makes the following replacements in the file named data.txt:

  • old1 is replaced with new1
  • old2 is replaced with new2

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

Example: How to Replace Multiple Strings in File in PowerShell

Suppose we have the following text file named basketball_info.txt that contains information about someone’s preference for different basketball teams:

Suppose that this file is saved in the following location:

  • c:\users\bobbi\documents\basketball_info.txt

Suppose that we would like to make the following replacements in the file:

  • Replace each occurrence of Lakers with Mavs.
  • Replace each occurrence of Warriors with Spurs.

We can use the following syntax to do so:

(Get-Content c:\users\bobbi\documents\basketball_info.txt).Replace('Lakers', 'Mavs').Replace('Warriors', 'Spurs') | Set-Content c:\users\bobbi\documents\basketball_info.txt

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

PowerShell replace multiple strings in file

We can then navigate to the file on our computer once more and view the file:

We can see that the following replacements have been made in the file:

  • Each occurrence of Lakers has been replaced with Mavs.
  • Each occurrence of Warriors has been replaced with Spurs.

Note: In this example we replaced two old strings with two new strings, but you can use similar syntax to chain together as many Replace() methods as you’d like to replace even more strings.

Related Tutorials

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

PowerShell: How to Replace Special Characters in String
PowerShell: How to Replace Text in String
PowerShell: How to Concatenate Strings

Leave a Reply