Text Processing – Remove Lines Before First Match

text processing

Using the regexp string, how can I remove all the lines before the first line that contains a match? e.g How can I change this:

lost
load
linux
loan
linux

into this:

linux
loan
linux

I tried:

echo "lost
load
linux
loan
linux" | sed -e 's/.*^li.*$//g'

but it returns this, not changing anything:

lost
load
linux
loan
linux

I'd like to make it work so that it won't output anything when there's no match.

Best Answer

One way, POSIXly:

$ echo "lost
load
linux
loan
linux" | sed -e/linux/\{ -e:1 -en\;b1 -e\} -ed

or shorter:

sed -n '/linux/,$p'

or even shorter:

sed '/linux/,$!d'

For readers who wonder why I prefer the longer over the shorter version, the longer version will only perform i/o over the rest of file, while using ranges can affect the performance if the 2nd address is a regex, and the regexes are trying to be matched more than is necessary.

Consider:

$ time seq 1000000 | sed -ne '/^1$/{' -e:1 -en\;b1 -e\}
=====
JOB sed -e '/^1$/,$d'
87%    cpu
0.11s real
0.10s user
0.00s sys

with:

$ time seq 1000000 | sed -e '/^1$/,/1000000/d'
=====
JOB sed -e '/^1$/,/1000000/d'
96%    cpu
0.24s real
0.23s user
0.00s sys

you can see the different between two versions. With complex regex, it's will be big difference.

Related Question