Let's assume I have the following input.
Header
thing0 some info
thing4 some info
thing4 some info
thing4 some info
thing2 some info
thing2 some info
thing3 some info
Now, I want to be able to append "foo" on the last successful match of "thing4" like this.
Header
thing0 some info
thing4 some info
thing4 some info
thing4 some info
foo
thing2 some info
thing2 some info
thing3 some info
The order is not necessarily guaranteed, but the sequential numbering in this example is just to show that there is a searchable keyword before certain lines of text and that they are are usually grouped together on input, but it is not guaranteed.
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