I have a program which prints out data in blocks. Each block is delimited by blank lines.

I would like to discard most blocks and only keep those blocks that contain something that matches a regex.

I can of course do it with a scripting language or a prgram, but that seems rather crude. Is there a better way to do it?

  • 6
    Can you give some sample input and output? – cuonglm May 1 '14 at 17:04

awk and perl have a special mode especially designed for that. Called the paragraph mode. In that mode, records are paragraphs, that is they are separated by sequences of empty lines.

For awk, it's with setting RS to the empty string:

awk -v RS= -v ORS='\n\n' '/regexp/'

With perl, it's with -00.

perl -00 -ne 'print if /regexp/'

It's usually possible to do this kind of thing fairly easily in awk, by setting the record separator to a double-newline, and then doing a regex match within the records. For example, if I have

block #1
this block doesnt' contain
anything I want to keep

here's a block
with some important stuff

here's another
block of stuff

and another


$ awk -vRS="\n\n" '/important/ {print}' blocktext.txt 
here's a block
with some important stuff

It would be easier to answer definitively if you provided an example.


Running pcregrep in multiline mode on @steeldriver's example:

pcregrep -Mo '\n\n\K(.|\n)*?important(.|\n)*?(?=\n\n)' file
here's a block
with some important stuff
  • That wouldn't match on the first and last paragraph though. – Stéphane Chazelas May 2 '14 at 7:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.