Try this:
$ tac infile | sed -n '/fish/,$p' |tac
In general case if you run below sed command, you will get all line from first matched pattern to end of input file.
$ sed -n '/fish/,$p' file
this is a some fish
this is a fishie
this is a fish
this is a lion
this is a cat
So my solution is: If we run tac
command on input file your last matched pattern will change to as first pattern. see the result of tac infile
:
$ tac infile
this is a cat
this is a lion
this is a fish
this is a fishie
this is a some fish
this is a goat
this is a cow
The tac
command is the same as cat
command, while tac
prints files in reverse order.
Now if we run our first sed command, you will get all lines first matched pattern to end of input file. like:
$ tac infile | sed -n '/fish/,$p'
this is a fish
this is a fishie
this is a some fish
this is a goat
this is a cow
Ok, finished. We only need to run tac
command again to reverse back the lines to original order:
$ tac infile | sed -n '/fish/,$p' |tac
this is a cow
this is a goat
this is a some fish
this is a fishie
this is a fish
Done!
With sed
:
sed -n '/R/,$!d; /S/q; p'
Example:
$ seq 20 | sed -n '/6/,$!d; /1/q; p'
6
7
8
9
Best Answer
You could do that with
ed
:the trick here is to try to replace
PATTERN
on1st
line with itself.ed
will error out if it can't find the specified pattern so,p
(print whole file) will only be executed if1s/PATTERN/&/
is successful.Or with
sed
:this
q
uits if the first line does not (!
) matchPATTERN
, otherwise itp
rints all lines.Or, as pointed out by Toby Speight, with GNU
sed
:Q
is the same asq
but it does not print the pattern space.