Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Append line after last match with sed

Tags:

regex

bash

sed

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.

like image 643
Mozzy Avatar asked Jun 19 '16 16:06

Mozzy


People also ask

How do you append a line at the end of a file using sed?

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.

How do you put a line after a sed pattern?

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.

How do you match a line at the end of sed?

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.


1 Answers

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.

like image 63
potong Avatar answered Sep 21 '22 09:09

potong