[olug] grep.pl

Jay Hannah jay at jays.net
Wed Feb 25 17:25:16 UTC 2004


AIX's GNU(?) utilities bite. Case in point: grep has a 2048 character line
limit. So, we're trying to grep big ugly logs and grep isn't working.
Then, just today, we hit a frustrating problem where grep is buffering
output, waiting for certain buffer sizes before printing. Well, that's
fine most of the time, but it wasn't fine today and there was no way to
tell AIX's grep not to do that.

So, I wrote grep.pl. It works where our AIX grep fails. I added a -n
switch 'cause I needed that today. I could add other handy switches if I
ever needed them (-l, -v -ponder-)...

Demo:
$ cat letters
a
b
c
d
e
f
$ grep.pl c letters
c
$ grep.pl -n c letters
3: c
$ cat letters | grep.pl c
c
$ cat letters | grep.pl -n c
3: c

The code:
#!/usr/bin/perl

use Getopt::Long;
use FileHandle;
STDOUT->autoflush;
STDERR->autoflush;

GetOptions (
   'n' => \$n
);

my $searchfor = shift;
while (<>) {
   $line_number++;
   next unless (/$searchfor/i);
   $line = $_;
   if ($n) {
      print "$line_number: ";
   }
   print $line;
}

Comments:
- Getopt::Long is cool.
- <> is cool and magically delicious
- Perl is cool.

j
Omaha Perl Mongers: http://omaha.pm.org





More information about the OLUG mailing list