Print line between two patterns when a certain pattern matched

Hello Friends,

I need to print lines in between two string when a keyword existed in those lines (keywords like exception, error, failed, not started etc).

for example,

input:

..
Begin Edr
ab12
ac13
ad14
bc23
exception occured
bd24
cd34
dd44
ee55
ff66
End Edr
Begin Edr
ab12
ac13
ad14
bc23
bd24
cd34
dd44
ee55
ff66
End Edr
..

..

I need the output:

Begin Edr
ab12
ac13
ad14
bc23
exception occured
bd24
cd34
dd44
ee55
ff66
End Edr

I found this on the net however i don't know how to modify

Pattern1="string1"
Pattern2="string2"

$ nawk -v p1=$(Pattern1) -v p2=${Pattern2} '{if ($1==p1) i=1}; {if ($1==p2) i=0}; i{print}' file

or

Pattern1="string1"
Pattern2="string2"

$ nawk -v p1=$(Pattern1) -v p2=${Pattern2} '{if ($1 ~ p1) i=1}; {if ($1 ~ p2) i=0}; i{print}' file

thanks in advance
Kind Regards

The code you found on the web is similar to

awk '/Pattern1/,/Pattern2/' file

If you want to print the lines only when an exception occurs, you could try something like this:

awk '/Begin Edr/{s="";p=0} {s=s $0 "\n"} /exception/{p=1} /End Edr/ && p{print s}' file

This is not too far off Subbeh's proposal, but it doesn't copy every single line to the temporary variable. Might be useful for large files that have sparse regions of interest in them.

awk     '/Begin Edr/,/End Edr/  {tmp=tmp (tmp?"\n":"") $0}   
         /End Edr/              {if (tmp ~ /exception|error|failed/) print /tmp; tmp=""} 
        ' file
1 Like