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, 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, p — Often-used commands
  3. Q — GNU Sed extended commands
  4. -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

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:

sed -n '1h;1!H;/foo/{g;p;q}'
  • 1h -- copy pattern space to hold space when on the first line
  • 1!H -- append pattern space to hold space when not on the first line
  • /foo/{...} -- on matching /foo/,
    • g -- copy hold space to pattern space
    • p -- print pattern space
    • q -- quit