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.
There are different ways to insert a new line in a file using sed, such as using the “a” command, the “i” command, or the substitution command, “s“. sed's “a” command and “i” command are pretty similar.
You have to use the “-i” option with the “sed” command to insert the new line permanently in the file if the matching pattern exists in the file.
Regular expressions can be anchored at the end of the line using $ (or at the beginning, using ^ ). Anchoring an expression at the start/end of a line forces it to match exactly there, and not just anywhere on the line. Save this answer.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With