PowerShell: How to Insert Line After Matching Pattern


Often you may want to use PowerShell to insert a new line into a file after a specific matching pattern.

You can use the following syntax to do so:

(Get-Content $my_file) | 
    Foreach-Object {
        $_
        if ($_ -match "Celtics") 
        {
            "Some New Text"
        }
    } | Set-Content $my_file

This particular example looks for the pattern “Celtics” in the lines of the file specified at the path in the $my_file variable and then adds a new line with the text “Some New Text” after this specific line.

If the string “Celtics” is not found on any line in the file then the new line will not be added.

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

Example: How to Insert Line After Matching Pattern in PowerShell

Suppose we have a text 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:

Suppose that we would like to find the line that contains the string “Celtics” and then insert a new line of text after this line in the file.

 We can use the following syntax to do so:

(Get-Content $my_file) | 
    Foreach-Object {
        $_
        if ($_ -match "Celtics") 
        {
            "Some New Text"
        }
    } | Set-Content $my_file

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

PowerShell insert line after match

Notice that a new line has been added to the file after the line containing the string “Celtics”, just as we specified.

Note that we used the Set-Content cmdlet to set the content of the existing file by outputting all of the existing content to the file along with the new line of text.

Note: You can find the complete documentation for the Set-Content cmdlet in PowerShell here.

Related Tutorials

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

PowerShell: How to Use Export-Csv with Append
PowerShell: How to Use Export-Csv with No Headers
PowerShell: How to Count Number of Lines in File

Leave a Reply