Ubuntu – Show all lines before a match

command linegreptext processing

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.

Best Answer

  • Including the match,

    sed '/foo/q' file
    

    It is better to quit sed as soon as a match is found, otherwise sed 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 the p command will be printed. Since the foo line triggers the quit action, it does not reach p and thus is not printed.

    • If your sed is GNU's, this can be simplified to

      sed '/foo/Q' file
      

References

  1. /foo/Addresses
  2. q, pOften-used commands
  3. QGNU Sed extended commands
  4. -nCommand-line options