Take the 2-minute tour ×
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.

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
5  
Can you give some sample input and output? –  Gnouc May 1 at 17:04
add comment

3 Answers 3

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
add comment

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

Then

$ 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
add comment

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 at 7:40
add comment

Your Answer

 
discard

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.