I want to show all lines before a match, not only 10, or 7, or 14 for example, as explained in How do I fetch lines before/after the grep result in bash?.
How can I do it? It doesn't matter if the matched line is included or not.
For example, instead of:
... | grep -B 10 -- "foo"
I want:
... | grep -B -- "foo"
But this last code doesn't work.
Including the match,
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,
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 toReferences
/foo/
— Addressesq
,p
— Often-used commandsQ
— GNU Sed extended commands-n
— Command-line optionsWith GNU sed. Print all lines, from the first to the line with the required string.
Here's a solution with
sed
, given the content of file.txt:command including pattern
output
excluding pattern
Current solutions except schrodigerscatcuriosity's print the file contents even when there's no match. schrodigerscatcuriosity's involves using
tac
and so requires reading the whole input before looking for matches.Here's another way to do it with just
sed
and printing only when there's a match:1h
-- copy pattern space to hold space when on the first line1!H
-- append pattern space to hold space when not on the first line/foo/{...}
-- on matching/foo/
,g
-- copy hold space to pattern spacep
-- print pattern spaceq
-- quitFreeBSD (including MacOS) version does have such feature.
Well
-B -1
works, it shows all the lines before the match from the beginning of the file.Same for
-A -1
, it shows all the lines after the match to the end of the file.May be useful for some, It doesn't work with GNU implementation included within Ubuntu.
To print all lines before the match,
You can use large enough number for
-B
option of grep. For example if your know that input size is no more than999
you can use it with-B
option: