Sed insert before first match

From Birnam Designs Wiki

Jump to: navigation, search

To insert a line before the first match using sed:

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

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

The second match limits the insert to only the line matching the regex -- the last line from the range. Therefore, it only happens once.

If you didn't match a second time, then the insert would happen to every line in the range.


See also:

Sed insert after last match

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