Linux: Using sed to insert lines before or after a match

The sed utility is a powerful utility for doing text transformations.  In this article, I will provide an example of how to insert a line before and after a match using sed, which is a common task for customizing configuration files.

I have also written a related article on setting and replacing values in a properties file using sed.

In these examples, we will be dealing with a text file named “text.txt” that contains the following content:

mykey=one
anothervalue=two
lastvalue=three

Replace a line when match found

The simplest case is replacing an entire line by finding the line that starts with the match.

sed 's/^anothervalue=.*/replace=me/g' test.txt

Which produces:

mykey=one
replace=me
lastvalue=three

Insert line after match found

Then we have the case where we need to insert a line after the match.

sed '/^anothervalue=.*/a after=me' test.txt

Which produces:

mykey=one
anothervalue=two
after=me
lastvalue=three

Insert a line before match found

Then we have the case where we need to insert a line before the match.

sed '/^anothervalue=.*/i before=me' test.txt

Which produces:

mykey=one
before=me
anothervalue=two
lastvalue=three

Insert multiple lines

And this might have slight variations depending on your POSIX compliance, but if you want to insert multiple lines, you can use ‘\n’ as shown below.

sed '/^anothervalue=.*/i before=me\nbefore2=me2' test.txt

Which produces:

mykey=one
before=me
before2=me2
anothervalue=two
lastvalue=three

 

REFERENCES

https://www.gnu.org/software/sed/

https://stackoverflow.com/questions/15559359/insert-line-after-first-match-using-sed (insert after match)

https://stackoverflow.com/questions/11694980/using-sed-insert-a-line-below-or-above-the-pattern (insert below match)

fabianlee.org, setting and replacing values in a properties file using sed

stackoverflow, use backslash to insert spaces into new line to insert

NOTES

To insert spaces at beginning of inserted line

sed '/^anothervalue=.*/i \ \ before=me' test.txt