Contextual grep

Ben Lotto ben at nsf1.mth.msu.edu
Thu Nov 16 06:32:52 AEST 1989


Here is a perl program I wrote to do a contextual grep, that is, it will
print out some number of lines before and after each matching line.  The
usage is
	congrep nlines pattern [files]
where
	nlines	is the number desired around each matching line
	pattern	is the pattern to be matched
	files	is a list of files to be searched (std input if empty).

I am new to perl, so this is probably not as efficient as it could be.
Please let me know if you find any problems or improvements.

----------CUT HERE------------------------------
#!/usr/brain/ben/bin/perl
$[ = 0;

die("Usage: congrep nlines regexp files\n") if ($#ARGV < 1);
$nlines = $ARGV[0] + 1;
shift;
$pat = $ARGV[0];
shift;

$#hist = $nlines;

$match = 0;

for ($i = 0; $i < $nlines; $i++) {
  $hist[$i] = <>;
  if ($match > 0) { $match++; }
  if ($hist[$i] =~ /$pat/) { $match = 1; }
  }

if ($match > 0) {
  for ($i = 0; $i < $nlines; $i++) {
    print($hist[$i]);
    }
  }
  
$next = 0;

while ($hist[$next] = <>) {
  if ($match > 0) { $match++; }
  if ($hist[$next] =~ /$pat/) { 
    if ($match == 0) {
      for ($i = 1; $i < $nlines; $i++) {
        print $hist[($next + $i) % $nlines];
        }
      }
    $match = 1;
    }
  if ($match > $nlines) {
    $match = 0;
    print "---\n" if ($nlines > 1);
    }
  if ($match > 0) { print $hist[$next]; }
  $next = ($next + 1) % $nlines;
  }
----------CUT HERE------------------------------
--

-B. A. Lotto  (ben at nsf1.mth.msu.edu)
Department of Mathematics/Michigan State University/East Lansing, MI  48824



More information about the Alt.sources mailing list