You can use the following syntax in PowerShell to remove all occurrences of a specific string in a text file:
Get-Content teams.txt | % {$_ -replace "East",""} | Out-File teams_new.txt
This particular example removes each occurrence of the string “East” from the file named teams.txt and save the results in a new file named teams_new.txt.
Here is how this syntax works:
- First, we use the Get-Content cmdlet to retrieve all lines from the file named teams.txt.
- Then, we use the % command as an alias for the ForEach-Object cmdlet along with the $_ command to retrieve the current line and the -replace operator to replace the string “East” with nothing.
- Lastly, we use the Out-File cmdlet to export these results to a new file named teams_new.txt.
The following example shows how to use this syntax in practice.
Example: How to Remove Specific String from Text File in PowerShell
Suppose that we have a file named teams.txt in our current directory that contains information about various basketball teams.
We can use the Get-Content cmdlet to view the contents of this file:

Suppose that we would like to remove each occurrence of the string “East” from the file.
We can use the following syntax to do so:
Get-Content teams.txt | % {$_ -replace "East",""} | Out-File teams_new.txt
The following screenshot shows how to use this syntax in practice:

Notice that when we use the Get-Content cmdlet to view the contents of the new file named teams_new.txt we can see that it contains all of the lines from the original file with the string “East” removed from each line.
Feel free to replace “East” with any other specific string that you’d like to replace in your own file.
Note: You can find the complete documentation for the Out-File cmdlet in PowerShell here.
Related Tutorials
The following tutorials explain how to perform other common tasks in PowerShell:
PowerShell: How to Add Text to Specific Line in a File
PowerShell: How to Add Text to Each Line in a File
PowerShell: How to Save Each Line of Text File as Array
