How to insert text after a certain string in a file?

Append line after match

  • sed '/\[option\]/a Hello World' input

Insert line before match

  • sed '/\[option\]/i Hello World' input

Additionally you can take backup and edit input file in-place using -i.bkp option to sed


Yes, it is possible with sed:

sed '/pattern/a some text here' filename

An example:

$ cat test
foo
bar
option
baz
$ sed '/option/a insert text here' test
foo
bar
option
insert text here
baz
$

With awk:

awk '1;/PATTERN/{ print "add one line"; print "\\and one more"}' infile

Keep in mind that some characters can not be included literally so one has to use escape sequences (they begin with a backslash) e.g. to print a literal backslash one has to write \\.

It's actually the same with sed but in addition each embedded newline in the text has to be preceded by a backslash:

sed '/PATTERN/a\
add one line\
\\and one more' infile

For more details on escape sequences consult the manual.