AWK: How to extract text lines between two strings

Hi.

I have a text test1.txt file like:

Receipt
Line1
Line2
Line3
End
 
Receipt
Line4
Line5
Line6
Canceled
 
Receipt
Line7
Line8
Line9
End
 
Line10
Line11
 
Receipt
Line12
Line13
Line14
Canceled

As result I need only lines between "Receipt" and "Canceled".

E.g.:

Receipt
Line4
Line5
Line6
Canceled
 
Receipt
Line12
Line13
Line14
Canceled

I have the following script:

awk '/Receipt/, $NF ~ /Canceled/ ' test1.txt

But this will extract other lines starting with "Receipt"

I found some other solution wotking with groups, but this is not helping me much:

awk '\
/Receipt/,/Canceled/ {
if (newgroup==0)
{print substr($0,index($0,"Receipt"))
newgroup=1}
else
{if (match($0,"Canceled"))
{print substr($0,1,index($0,"Canceled")-1)
newgroup=0}
else
print
}
}' test1.txt

Any ideas appreciated. :slight_smile:

why bother with long code use the comma operator as below:-

nawk '/Receipt/, /Canceled/' file.txt

you can use nawk,gawk,/usr/xpg4/bin/awk

:D:D:D:D:D

If the groups are separated by blank lines, then:

awk 'BEGIN{FS="\n";RS="";ORS="\n\n"}/Receipt.*Canceled/'
awk '/Receipt/{s=x}{s=s$0"\n"}/Canceled/{print s}'

Thanks a lot!
That's exactly what I need. :b:

Thanks again Scrutinizer for previous solution, but how to modify it
to get only lines between "Receipt" and "Canceled"
if any line in between contains pattern "Line13"?

Using previous example I would like to have only:

Receipt
Line12
Line13
Line14
Canceled

With a slightly change of the code of Scrutinizer:

awk '/Receipt/{s=x}{s=s$0"\n"}/Line13/{p=1}/Canceled/ && p{print s;exit}' file

Thank you, Franklin52!

It works, but it extracts only first occurance of /Receipt/, /Canceled/ block with Line13 inside.

Receipt
Line13
Line3
Canceled

In my case I have several "blocks" /Receipt/, /Canceled/
and in some blocks there is a text "Line13".

E.g.
Initial file:

Receipt
Line13
Line3
Canceled
 
Receipt
Line4
Line5
Line6
Canceled
 
Receipt
Line7
Line13
End
 
Receipt
Line12
Line13
Line14
Canceled 

Result file:

Receipt
Line13
Line3
Canceled
 
Receipt
Line12
Line13
Line14
Canceled

Should be something like:

awk '
/Receipt/ {s=x} 
{s=s$0"\n"} 
/Line13/ {p=1} 
/Canceled/ && p {print s;s=x;p=0}
' file

Thank you very much Franklin52!