2

How can I print the contents of a file minus everything including and below the line above the first occurrence of a pattern?

Say the pattern is "^Previous" on line 15; then I would like to print lines 1--13.

Toothrot
  • 3,435

2 Answers2

5

sed can do this all by itself:

sed -n '$!N;/.*PATTERN.*/q;P;D' infile

It's very simple: turn on silent mode, use a sliding window (via N and D, so that there are always two lines in the pattern space), quit if encountering PATTERN otherwise Print the first line in the pattern space and restart the cycle.

With gnu sed it's even shorter as it can Quit without auto-printing so you can skip silent mode:

sed  '$!N;/.*PATTERN.*/Q;P;D' infile
don_crissti
  • 82,805
2

How about KISS

sed '1,/^Previous/!d' file | head -n -2
steeldriver
  • 81,074