PowerShell: How to Replace Entire Line that Contains Pattern


Often you may want to use PowerShell to replace an entire line in a text file that matches a pattern.

You can use the following syntax to do so:

$line = (Select-String "Rockets" teams.txt).line

Get-Content teams.txt | ForEach { $_ -replace $line, "Western Team" } | Set-Content teams_new.txt

This particular example replaces the entire line that contains the pattern “Rockets” in the file named teams.txt with the new text “Western Team” and saves the results to a new file named teams_new.txt.

Note that we use the Select-String cmdlet with the line property to first select the entire line in the teams.txt file that contains the pattern “Rockets” and store this line in a variable named $line.

We then use the -replace operator to replace the text in this specific line with the text “Western Team” instead.

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

Example: How to Replace Entire Line that Contains Pattern in PowerShell

Suppose we have a file in our current directory named teams.txt 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 replace the entire line that contains the pattern “Rockets” with the text “Western Team” instead.

We can use the following syntax to do so:

$line = (Select-String "Rockets" teams.txt).line

Get-Content teams.txt | ForEach { $_ -replace $line, "Western Team" } | Set-Content teams_new.txt

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

PowerShell replace entire line that matches pattern

Notice that when we use the Get-Content cmdlet to view the contents of the teams_new.txt file we can see that the entire line that contained the pattern “Rockets” has been replaced with “Western Team” instead.

All other lines in the file have remained unchanged.

Feel free to replace “Rockets” with any pattern that you’d like to search for in your own file.

Related Tutorials

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

PowerShell: How to Replace Text in String
PowerShell: How to Replace Specific Text in Multiple Files
PowerShell: How to Extract Text Between Two Strings
PowerShell: How to Check if String Exists in List of Strings

Leave a Reply