How to Use sed to Insert Multiple Lines After Match


Often you may want to use sed to insert multiple lines into a file after a specific line that matches a pattern.

You can use the following syntax to do so:

sed "/A009/aline1\nline2\nline3" employees.txt

This particular example will insert three lines with the text line1, line2 and line3 immediately after the line that matches the pattern A009 in the file named employees.txt.

Note that we use the a command to “append” new text to the file and we use \n to specify where new lines begin.

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

Example: Use sed to Insert Multiple Lines After Match

Suppose that we have a file named employees.txt that contains the ID values for various employees at some company.

We can use the cat command to view the contents of this file:

Now suppose that we would like to insert three new lines after the line that matches the pattern A009 in the file.

We can use the following syntax to do so:

sed "/A009/aline1\nline2\nline3" employees.txt

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

sed insert multiple lines after match

Notice that three new lines with the text line1, line2 and line3 have been inserted into the file immediately after the line that matched the pattern A009.

Note that if you would like to save these changes to the file in-place then you can add the -i flag as follows:

sed -i "/A009/aline1\nline2\nline3" employees.txt

This will save the changes to the employees.txt file in-place.

Related Tutorials

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

How to Use sed to Insert Line at Specific Line Number
How to Use sed to Insert Empty Line in a File
How to Use sed to Insert Line with Leading Spaces

Leave a Reply