PowerShell: How to Replace Every Occurrence of String in File


You can use the following basic syntax to replace every occurrence of a string in a file using PowerShell:

(Get-Content c:\doc\data.txt).Replace('old', 'new') | Set-Content c:\doc\data.txt

This particular example replaces every occurrence of the string “old” with “new” in the file named data.txt.

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

Example: How to Replace Every Occurrence of String in File in PowerShell

Suppose we have the following text file named basketball_info.txt that contains information about someone’s favorite basketball team:

Suppose that this file is saved in the following location:

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

Suppose that we would like to replace each occurrence of the text “Mavs” with the text “Lakers” instead.

We can use the following syntax to do so:

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

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

PowerShell replace string in file

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

We can see that every occurrence of “Mavs” in the file has been replaced with “Lakers” instead.

Note that if you would like to remove every occurrence of a specific string in a file, then you can simply replace the string with nothing.

For example, you can use the following syntax to simply remove every occurrence of “Lakers” from the file:

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

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

We can then navigate to this file on our computer again to view it:

We can see that every occurrence of “Lakers” has simply been removed from the file.

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