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,691
  • 4
  • 21
  • 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
  • 111,086
  • 29
  • 224
  • 214
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
  • 713,503
  • 59
  • 514
  • 593
  • 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
  • 39,326
  • 11
  • 49
  • 54
1
sed '/Hello/ a/
Your message with /
New line' YourFile

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

NeronLeVelu
  • 9,588
  • 1
  • 22
  • 41