Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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?

share|improve this question
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/'
share|improve this answer

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.

share|improve this answer

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
share|improve this answer
That wouldn't match on the first and last paragraph though. – Stéphane Chazelas May 2 '14 at 7:40

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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