Using awk or sed, how to get contents between two parameters , parameters occurs multiple time in a file
For instance, file contents
Entering AAA
12
Entering BBB
13
Leaving AAA
14
Leaving AAA
15
Leaving AAA
16
Leaving BBB
Currently I am using
cat 1.txt |sed -n '/Entering AAA/,/Leaving AAA/ p'
with this , I am getting contents between first occurrence of "Entering AAA" and first occurrence of "Leaving AAA" ie
Entering AAA
12
Entering BBB
13
Leaving AAA
But , I want contents from first occurrence of "Entering AAA" to last occurrence of "Leaving AAA"
Expected output :
Entering AAA
12
Entering BBB
13
Leaving AAA
14
Leaving AAA
15
Leaving AAA
Kindly help.
In any awk using a 2-pass approach:
$ awk 'NR==FNR{if (/Leaving AAA/) end=NR; next} /Entering AAA/{f=1} f; FNR==end{exit}' file file
Entering AAA
12
Entering BBB
13
Leaving AAA
14
Leaving AAA
15
Leaving AAA
Alternatively doing it in one pass with GNU awk for multi-char RS and RT:
$ awk -v RS='Entering AAA.*Leaving AAA' 'RT{print RT}' file
Entering AAA
12
Entering BBB
13
Leaving AAA
14
Leaving AAA
15
Leaving AAA
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