Seeking a grep-like script

Dave Cross davorg at gmail.com
Thu Jun 24 09:25:33 UTC 2010


On 10 June 2010 14:26, Bill Davidsen <davidsen at tmr.com> wrote:
> Timothy Murphy wrote:
>>
>> I'm looking for a grep-like script that searches for a given word,
>> and returns the paragraphs in which it appears (rather than the lines),
>> where a paragraph is defined as the material between 2 blank lines.
>>
>> All suggestions gratefully received.
>>
> It would be relatively easy to do in perl, suggested logic is to read in a
> paragraph, check for the word, print if found. Only takes a few lines of
> code.
>
> If by "looking for" you mean finding a script which does you what you want,
> I don't know where you find it, it's a bit trivial to bother to save.
>
> Sample attached.

The code becomes even easier if you put Perl into "paragraph mode".

#!/use/bin/perl

use strict;
use warnings;

$/ = ''; # paragraph mode - see "perldoc perlvar"

# Assume first argument is word to find
my $word = shift;

while (<>) {
  print if /\b\Q$word\b/; # \Q is a safety measure - escape metacharacters
}



Cheers,

Dave...


More information about the users mailing list