Sed append after a line containing multiple unordered strings

sed

I'm trying to use sed to append appendstring after a line that contains both Hello and World.

Hello something here World
World fsf Hello

This works if I do consider order:

sed -i '/Hello*World\|World*Hello/a appendstring' file

But if I have many strings to match and they are not in order, this is definitely not effective.

Then I tried solutions from another link which discussed deleting a line that contains both strings without considering their order.

https://stackoverflow.com/questions/28561519/delete-lines-that-contain-two-strings

However,

sed -i '/Hello/!b;/World/d' file

This does not even work for deletion.

The following one, also one of the answers to that question:

sed -i '/Hello/{/World/d}' file

works, so I tried to implement it to append. Using:

sed -i '/Hello/{/World/a} appendstring' file

But received error:

sed: -e expression #1, char 0: unmatched `{'

Update:
The post in the link stated the solution with !b, and it was not working in cshell because of the exlamation mark, but it is working in sh and bash. And it can also be easily extended to inserting many lines when running sed inside a script and the appending a large paragraph.

sed -i '/Hello/!b; /World/a \
addline \
addanotherline ' file

Best Answer

You almost had it with:

sed -i '/Hello/{/World/a} appendstring' file

You need to separate your arguments. Use -e, like so:

sed -i -e '/Hello/{/World/a appendstring' -e '}' file

Note that using the append command without a newline is a GNU extension, as is the -i switch.


To do this more portably, and considering as well the possibility of multiple strings to match, try:

sed '/multiple/{/words/{/to/{/match/ s/$/append this/;};};}' file > newfile
mv newfile file

Since you're using GNU Sed already, just use:

sed -i -e '/multiple/{/words/{/to/{/match/ a append this' -e 'a and also this' -e 'a oh and this too' -e '};};}' file
Related Question