Jeanno
Jeanno

Reputation: 2859

Insert text in the middle of a text file after the first occurence of a search string using sed

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,

Upvotes: 0

Views: 3034

Answers (4)

NeronLeVelu
NeronLeVelu

Reputation: 10039

sed '/Hello/ a/
Your message with /
New line' YourFile

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

Upvotes: 1

Jotne
Jotne

Reputation: 41460

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.

Upvotes: 1

devnull
devnull

Reputation: 123608

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? 

Upvotes: 1

anubhava
anubhava

Reputation: 785541

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? 

Upvotes: 1

Related Questions