Append line after last match with sed

Using single awk you can do:

awk 'FNR==NR{ if (/thing4/) p=NR; next} 1; FNR==p{ print "foo" }' file file

Header
thing0 some info
thing4 some info
thing4 some info
thing4 some info
foo
thing2 some info
thing2 some info
thing3 some info

Earlier Solution: You can use tac + awk + tac:

tac file | awk '!p && /thing4/{print "foo"; p=1} 1' | tac

This might work for you (GNU sed):

sed '1h;1!H;$!d;x;s/.*thing4[^\n]*/&\nfoo/' file

Slurp the file into memory and use the greed of the regexp to place the required string after the last occurrence of the required pattern.

A more efficient (uses minimum memory) but harder to understand is:

sed '/thing4[^\n]*/,$!b;//{x;//p;g};//!H;$!d;x;s//&\nfoo/' file

The explanation is left to the reader to puzzle over.

Tags:

Regex

Bash

Sed