maddie maddie - 1 month ago 19
Bash Question

Unix awk command to return all matching lines

I have a file which looks like the below -

A
B
C
D
E

-----

A
B
C
D
C

---

X
Y
A
B
XEC

---


When the fifth row of each block is/contains E, I want the previous 4 lines to be returned. I wrote the below command but it is buggy

awk '{a[NR]=$0} $0~s {f=NR} END {print a[f-4]; print a[f-6]; print a[f-8];}' s="E" file.txt


But it is returning only the last match. I want all the matched lines to be returned.

For the above entries, the output needs to be

A
B
C
D
---

X
Y
A
B


Is there any other way to achieve this?

PS. PS.
Answer Source
awk -v RS='\n\n[-]+\n\n*' -v FS="\n" '$5 ~ /E/{printf "%s\n%s\n%s\n%s\n---\n",$1,$2,$3,$4}' inputfile
A
B
C
D
---
X
Y
A
B
---