Extract lines between two patterns from a file [duplicate]

This can be an approach:

$ awk '/pattern1/ {p=1}; p; /pattern2/ {p=0}' file
********************************* Results *********************************
SUCCEEDED
...
...
some text
***************************************************************************
  • When it finds pattern1, then makes variable p=1.
  • it just prints lines when p==1. This is accomplished with the p condition. If it is true, it performs the default awk action, that is, print $0. Otherwise, it does not.
  • When it finds pattern2, then makes variable p=0. As this condition is checked after p condition, it will print the line in which pattern2 appears for the first time.

If you want an exact match of the lines:

$ awk '$0=="pattern1" {p=1}; p; $0=="pattern2" {p=0}' file

Test

$ cat a
***************************************************************************
text line # n-2
pattern1
********************************* Results *********************************
SUCCEEDED
...
...
some text
***************************************************************************
pattern2
text line # m+2
pattern2
***************************************************************************
$ awk '/pattern1/ {p=1}; p; /pattern2/ {p=0}' a
pattern1
********************************* Results *********************************
SUCCEEDED
...
...
some text
***************************************************************************
pattern2

Leave a Comment