PowerShell: How to Remove Lines Containing Specific String


Often you may want to use PowerShell to remove all lines in a file that contain a specific string.

You can use the following syntax to do so:

Get-Content teams.txt | Where-Object { -not $_.Contains('West') }

This particular example removes all lines from the file named teams.txt that contain the string ‘West’ anywhere in the line.

Note that you can also use the Set-Content cmdlet to save these changes to a new file:

Get-Content teams.txt | Where-Object { -not $_.Contains('West') } | Set-Content teams_new.txt

This particular example will save the changes to a new file named teams_new.txt.

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

Example: How to Remove Lines Containing a Specific String in PowerShell

Suppose 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:

Now suppose that we would like to remove all lines from the file that contain the string ‘West’ anywhere in the line.

We can use the following syntax to do so:

Get-Content teams.txt | Where-Object { -not $_.Contains('West') }

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

PowerShell remove lines containing string

Notice that this removes all lines that contain the string ‘West’ anywhere in the line.

Note that we could also use the following syntax to save these changes to a new file named teams_new.txt:

Get-Content teams.txt | Where-Object { -not $_.Contains('West') } | Set-Content teams_new.txt

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

PowerShell remove lines that contain string

Notice that when we use the Get-Content cmdlet to view the contents of the file named teams_new.txt we can see that it contains the same content as the original file with all lines that contain ‘West’ removed.

Related Tutorials

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

PowerShell: How to Extract Text Between Two Strings
PowerShell: How to Replace Text with Wildcard
PowerShell: How to Replace Special Characters in String

Leave a Reply