Sed insert after last match

From Birnam Designs Wiki

Jump to: navigation, search

To insert a line before the first match using sed:

sed -n -e '{ /RE/,$ {
	/RE/ !{
                   0,/./ i\
new line here
} } }' file

The first match, /RE/,$ is a range that says to operate only from the first match to the last line in the file.

The second match is negated, so that it only operates on lines that don't match the regex -- it operates on lines following the matches.

The third match just takes the first line only from the non-match set, which is the first non-matching line in the file. An insert will place the new line between the last match and the first non-match. If you left this match out, the insert would occur on every line after the matches.


See also:

Sed insert before first match

Share This!
This page was last modified on 11 February 2010, at 20:08. This page has been accessed 965 times.