Path: utzoo!utgpu!jarvis.csri.toronto.edu!rutgers!ucsd!usc!samsung!uunet!tank!eecae!cps3xx!cps3xx.egr.msu.edu!ben From: ben@nsf1.mth.msu.edu (Ben Lotto) Newsgroups: alt.sources Subject: Contextual grep Message-ID: Date: 15 Nov 89 19:32:52 GMT Sender: usenet@cps3xx.UUCP Reply-To: ben@nsf1.mth.msu.edu Distribution: alt Organization: Michigan State University Lines: 63 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@nsf1.mth.msu.edu) Department of Mathematics/Michigan State University/East Lansing, MI 48824