Insert line after first match using sed

user2150250 picture user2150250 · Mar 21, 2013 · Viewed 289.1k times · Source

For some reason I can't seem to find a straightforward answer to this and I'm on a bit of a time crunch at the moment. How would I go about inserting a choice line of text after the first line matching a specific string using the sed command. I have ...

CLIENTSCRIPT="foo"
CLIENTFILE="bar"

And I want insert a line after the CLIENTSCRIPT= line resulting in ...

CLIENTSCRIPT="foo"
CLIENTSCRIPT2="hello"
CLIENTFILE="bar"

Answer

Gilles Quenot picture Gilles Quenot · Mar 21, 2013

Try doing this using GNU sed:

sed '/CLIENTSCRIPT="foo"/a CLIENTSCRIPT2="hello"' file

if you want to substitute in-place, use

sed -i '/CLIENTSCRIPT="foo"/a CLIENTSCRIPT2="hello"' file

Output

CLIENTSCRIPT="foo"
CLIENTSCRIPT2="hello"
CLIENTFILE="bar"

Doc

  • see sed doc and search \a (append)