Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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?

share|improve this question
    
Duplicate of (Stack Overflow) : stackoverflow.com/questions/15559359/… –  John WH Smith Aug 14 at 9:44

3 Answers 3

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.

share|improve this answer

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.
share|improve this answer

POSIXly:

$ sed -e "/'test message1'/s//&\\
'testing testing'/" file
'test message1'
'testing testing'
'test message2'
'test message3'
'test message4'
'test message5'
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.