I need to extract particular lines between two matching patterns from a huge file.
Let's say pattern1
(unique in a file) matches a particular line # n
and pattern2
(not unique in a file) matches line # m
next immediate match after line # n
. Then I want to extract all lines between and including line #n to #m
Sample File contents
***************************************************************************
text line # n-2
text line # n-1
********************************* Results *********************************
SUCCEEDED
...
...
some text
***************************************************************************
text line # m+1
text line # m+2
***************************************************************************
Desired Output
********************************* Results *********************************
SUCCEEDED
...
...
some text
***************************************************************************
It would be appreciated if you could help me solve this problem
Using sed
:
$ sed '/start_pattern_here/,/end_pattern_here/!d' inputfile
and in OP's specific case:
$ sed '/[*]* Results [*]*/,/^[*]*$/!d' inputfile
********************************* Results *********************************
SUCCEEDED
...
...
some text
***************************************************************************
Assuming that the unique pattern was *** Results ***
and the non-unique one was ********
.
This can be an approach:
$ awk '/pattern1/ {p=1}; p; /pattern2/ {p=0}' file
********************************* Results *********************************
SUCCEEDED
...
...
some text
***************************************************************************
pattern1
, then makes variable p=1.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.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
$ 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With