Show all lines before a match
Including the match,
sed '/foo/q' file
It is better to quit
sed
as soon as a match is found, otherwisesed
would keep reading the file and wasting your time, which would be considerable for large files.Excluding the match,
sed -n '/foo/q;p' file
The
-n
flag means that only lines that reach thep
command will be printed. Since thefoo
line triggers theq
uit action, it does not reachp
and thus is not printed.If your
sed
is GNU's, this can be simplified tosed '/foo/Q' file
References
/foo/
— Addressesq
,p
— Often-used commandsQ
— GNU Sed extended commands-n
— Command-line options
With GNU sed. Print all lines, from the first to the line with the required string.
sed '0,/foo/!d' file
Here's a solution with sed
, given the content of file.txt:
bar
baz
moo
foo
loo
zoo
command including pattern
tac file.txt | sed -n '/foo/,$p' | tac
output
bar
baz
moo
foo
excluding pattern
tac file.txt | sed -n -e '/foo/,$p' | tac | sed -n '/foo/!p'
bar
baz
moo