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.



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

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
  • Hi expert I'm faced with a new problem could you help to check: unix.stackexchange.com/questions/320485/… – phonycollectibles Nov 2 '16 at 7:46
  • @phonycollectibles, seems like the same problem to me. See the edit to this answer. – Wildcard Nov 2 '16 at 8:09
  • yeah it works also, but when writing things like this in a script and I happened to have to insert a text with many lines. In order to look nicer, how do make the insertion inside sed remain to be many lines instead of concatenating them in one line? – phonycollectibles Nov 2 '16 at 8:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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