Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find specific pattern and print complete text block using awk or sed

Tags:

regex

sed

awk

How can find a specific number in a text block and print the complete text block beginning with the key word "BEGIN" and ending with "END"? Basically this is what my file looks like:

BEGIN
A: abc
B: 12345
C: def
END

BEGIN
A: xyz
B: 56789
C: abc
END

BEGIN
A: ghi
B: 56712
C: pqr
END

[...]

If I was looking for '^B: 567', I would like to get this output:

BEGIN
A: xyz
B: 56789
C: abc
END

BEGIN
A: ghi
B: 56712
C: pqr
END

I could use grep here (grep -E -B2 -A2 "^B: 567" file), but I would like to get a more general solution. I guess awk or sed might be able to do this!?

Thanks! :)

like image 883
edloaa Avatar asked Oct 08 '13 20:10

edloaa


2 Answers

$ awk -v RS= -v ORS='\n\n' '/\nB: 567/' file
BEGIN
A: xyz
B: 56789
C: abc
END

BEGIN
A: ghi
B: 56712
C: pqr
END

Note the \n before B to ensure it occurs at the start of a line.This is in place of the ^ start-of-string character you had originally since now each line isn't it's own string. You need to set ORS above to re-insert the blank line between records.

like image 185
Ed Morton Avatar answered Sep 30 '22 04:09

Ed Morton


This might work for you (GNU sed):

sed -n '/^BEGIN/{x;d};H;/^END/{x;s/^B: 567/&/mp}' file

or this:

sed -n '/^BEGIN/!b;:a;$!{N;/\nEND/!ba};/\nB: 567/p' file
like image 22
potong Avatar answered Sep 30 '22 05:09

potong