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

Right now I’m using

echo "Hello World" >> file.txt

to append some text to a file but I also need to add text below a certain string let’s say [option], is it possible with sed?

EG:

Input file

Some text
Random
[option]
Some stuff

Output file

Some text
Random
[option]
*inserted text*
Some stuff

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
$
Answered By: devnull

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

Answered By: Rahul Patil

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.


Also, to address some of the comments: the above commands DO NOT edit the file in place, they just print the result to the standard output. To actually modify the input file you would either use the -i switch if your awk/sed support it (consult the manual) or redirect to a temporary file then overwrite the original e.g.

cmd infile > outfile
mv outfile infile

Or use ed/ex which can edit the files in-place on all platforms:

ex -s infile <<IN
/PATTERN/a
add one line
and one more
.
w
q
IN

Remember: with ed/sed/ex, a appends and i inserts; with awk, to insert, move the 1 to the end.

Answered By: don_crissti

This can also be achieved using the ed utility. It’s easier to use sed but nice to be familiar with an additional utility (I came to this page, specifically looking how to achieve this using ed; I already knew how to do it in sed).

For your example file (printed with line numbers for reference):

 1  Some text
 2  Random
 3  [option]
 4  Some stuff

The ed commands to achieve the suggested output would be:

4i
*inserted text*
.
w
q

Explanation:

  1. go to line 4, start insert mode (i)
  2. add *inserted text* (including the newline)
  3. exit insert mode (.)
  4. write the file (w) and quit ed (q)

You can put this all together in one command using a here string:

ed filename.txt <<< '4i
*inserted text*
.
w
q
'
Answered By: Mark
Categories: Answers Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.