Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get contents between two parameters , parameters occurs multiple time in a file

Tags:

grep

shell

sh

sed

awk

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.

like image 397
Harsha K L Avatar asked Dec 06 '25 13:12

Harsha K L


1 Answers

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
like image 119
Ed Morton Avatar answered Dec 08 '25 07:12

Ed Morton



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!