15

Actually I have a file called test1.txt.

In that file I have the following five lines:

 'test message1'
 'test message2'
 'test message3'
 'test message4'
 'test message5'

Now I want to add a new line 'testing testing' into test1.txt file, after the 'test message1' line. How to do that?

peterh
  • 9,731
Beginner
  • 1,960

3 Answers3

22

This is what the a command does:

sed -e "/test message1/a\\
'testing testing'" < data

This command will:

Queue the lines of text which follow this command (each but the last ending with a \, which are removed from the output) to be output at the end of the current cycle, or when the next input line is read.

So in this case, when we match a line with /test message1/, we run the command append with the text argument "'testing testing'", which becomes a new line of the file:

 'test message1'
 'testing testing'
 'test message2'
 'test message3'
 'test message4'
 'test message5'

You can insert multiple lines by ending each of the non-final lines with a backslash. The double backslash above is to prevent the shell from eating it; if you're using it in a standalone sed script you use a single backslash. GNU sed accepts a single line of text immediately following a as well, but that is not portable.

Michael Homer
  • 76,565
  • 1
    why the double backslash at the end of the first line? – vwvan Apr 04 '19 at 05:10
  • 2
    @vwvan With the single backslash, and then a \n as the first character on the next line, I'd just get an n inserted (instead of a newline). So maybe the double backslash ensures that if the first character is an escape sequence, it will be inserted instead of grouped with the backslash next to the a command. – Levi Uzodike Mar 03 '20 at 22:08
4

With sed:

sed "s/'test message1'/'test message1'\n'testing testing'/g"
  • Searches for 'test message1'
  • Replaces with 'test message1' [new line] 'testing testing'.

From this answer, you could also use:

sed "/'test message1'/a 'testing testing'"
  • Searches for 'test message1'
  • Appends 'testing testing' after the matches.
John WH Smith
  • 15,880
0

POSIXly:

$ sed -e "/'test message1'/s//&\\
'testing testing'/" file
'test message1'
'testing testing'
'test message2'
'test message3'
'test message4'
'test message5'
cuonglm
  • 153,898