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.

  • there is no mention of excluding the line above the match in the other question – Toothrot Jul 26 '18 at 12:05
  • Please provide an example – roaima Jul 26 '18 at 13:09
  • @roaima, an example of what? I have already given an example. – Toothrot Jul 26 '18 at 13:18
  • You haven't given an example. You've told us what you want. Please include a short example of a file that contains your desired exclusion pattern, and then show the desired result. – roaima Jul 26 '18 at 14:48
  • 1
    @roaima, the 2nd paragraph is an example. if you want a different kind of example, you should give a reason. – Toothrot Jul 26 '18 at 14:57

How about KISS

sed '1,/^Previous/!d' file | head -n -2

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.