I have a file which contains a list of car manufacturers:
$ cat cars
subaru
mercedes
porche
ferrari
audi
mercedes
BMW
ferrari
toyota
lexus
mercedes
VW
$
I would like to print all the lines between mercedes
and ferrari
so the desired output is:
mercedes
porche
ferrari
mercedes
BMW
ferrari
My first thought was to use gsed -n '/mercedes/,/ferrari/p' cars
, but this does obviously not work because sed
processes file line by line and it has no way to know that last mercedes
in this file is not followed with ferrari
. I was able to accomplish this with gsed -n '/mercedes/h;/^[^mercedes].*$/H;/ferrari/{g;p}' cars
, but I see few problems with this solution:
1) if the end-marker is present, but start-marker is not. For example if last mercedes
in my file is replaced with ferrari
, then output is wrong.
2) one can not use regular expressions in [^mercedes]
part. For example if I would like to use both mercedes
and mg-motors
as a start marker, then I can't use [^m.*s]
regular expression as it would match literal characters m
, .
. *
and s
.
Is there a smarter way to print text between two markers with sed
only if the second marker exists? Should one use awk
in order to solve this problem?