How to Use sed to Insert a Line After Match


Often you may want to use sed to insert a line after the first line that matches a particular pattern in a file.

You can use the following methods to do so:

Method 1: Insert a Line After All Matches

sed '/A00/a D55John' employees.txt

This particular example inserts a line with the string D55John after each line in the employees.txt file that matches the pattern A00.

Method 2: Insert a Line After First Match Only

sed '0,/A00/!b;//aD55John' employees.txt

This particular example inserts a line with the string D55John only after the first line in the employees.txt file that matches the pattern A00.

The following examples show how to use each method in practice with a file named employees.txt that contains the ID numbers for various employees at some company:

Example 1: Use sed to Insert a Line After All Matches

Suppose that we would like to insert a line that contains the string D55John after each line in the employees.txt file that contains the pattern A00 anywhere in the line.

We can use the following syntax to do so:

sed '/A00/a D55John' employees.txt

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

sed insert line after all matches in file

Notice that a line with the string D55John has been inserted after each line in the file that contained the pattern A00.

Note: If you would like to modify the file in-place, then you can add the -i flag as follows:

sed -i '/A00/a D55John' employees.txt

Example 2: Use sed to Insert a Line After First Match Only

Suppose that we would like to insert a line that contains the string D55John only after the first line in the employees.txt file that contains the pattern A00.

We can use the following syntax to do so:

sed '0,/A00/!b;//aD55John' employees.txt

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

sed insert line after first match only

Notice that a line with the string D55John has been inserted only after the first line in the file that contained the pattern A00.

Related Tutorials

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

How to Use sed to Delete Specific Line Numbers from File
How to Use sed to Replace All Occurrences of Pattern
How to Use sed to Replace All Text After Match
How to Use sed to Extract All Lines Containing a Pattern

Leave a Reply