0

I am wondering if it is possible to insert some text in the middle of a text file after the first occurrence of a search string using GNU sed.

So for example, if the search string is "Hello", I would like to insert a string right after the first occurrence of "Hello" on a new line

Hello John, How are you?
....
....
....
Hello Mary, How are you doing? 

The string would be entered right after "Hello John, How are you?" on a new line

Thanks,

Jeanno
  • 2,769
  • 4
  • 23
  • 31
  • possible duplicate of [How do I add a line of text to the middle of a file using bash?](http://stackoverflow.com/questions/6739258/how-do-i-add-a-line-of-text-to-the-middle-of-a-file-using-bash) – Big McLargeHuge May 25 '15 at 13:51

4 Answers4

1

You could say:

sed '/Hello/{s/.*/&\nSomething on the next line/;:a;n;ba}' filename

in order to insert a line after the first occurrence of the desired string, e.g. Hello as in your question.

For your sample data, it'd produce:

Hello John, How are you?
Something on the next line
....
....
....
Hello Mary, How are you doing? 
devnull
  • 118,548
  • 33
  • 236
  • 227
1

Using sed:

sed '/Hello John, How are you?/s/$/\nsome string\n/' file
Hello John, How are you?
some string

....
....
....
Hello Mary, How are you doing? 
anubhava
  • 761,203
  • 64
  • 569
  • 643
  • Thanks for your answer, I picked devnull's answer because it is more general. – Jeanno Feb 03 '14 at 17:26
  • Not sure what is general in mine or his answer, both are producing same output. But for better portable solutions always consider awk over sed. – anubhava Feb 03 '14 at 17:28
1

Using awk

awk '/Hello/ && !f {print $0 "\nNew line";f=1;next}1' file
Hello John, How are you?
New line
....
....
....
Hello Mary, How are you doing?

This search for sting Hello and if flag f is not true (default at start)
If this is true, print the line, print extra text, set flag f to true, skip to next line.
Next time Hello is found flag f is true and nothing extra will be done.

Jotne
  • 40,548
  • 12
  • 51
  • 55
1
sed '/Hello/ a/
Your message with /
New line' YourFile

a/ for append (after) your pattern to find, i/ for instert (before)

NeronLeVelu
  • 9,908
  • 1
  • 23
  • 43