in reply to Emulating GNU grep -A and -B switches with perl (was: linux grep feature)
use strict; use warnings; use Getopt::Std; our %opts; getopts('A:B:n',\%opts); die "USAGE: $0 [-n] [-An] [-Bn] pattern [file] ..." unless @ARGV; my $pattern = shift; my @buffer; my @matches; my $nextmatch; my $prevmatch; my $linenum; my $shownames; my $fname; my $showlines = $opts{n}; my $behind = $opts{B} || 0; my $after = $opts{A} || 0; my $bufsize = 1 + $behind; if (@ARGV == 0) { procfile("-"); } else { $shownames = 1 if @ARGV > 1; procfile($fname) while ($fname = shift @ARGV); } sub procfile { $prevmatch = -2 - $after; $linenum = 0; $nextmatch = 0; my $f = shift; unless (open IN, "<$f") { warn "$0: $f: $!\n"; return; } while (<IN>) { push @buffer, $_; my $matched = m/$pattern/o; push @matches, $matched; $linenum++; $nextmatch = $linenum if $matched; if (@buffer >= $bufsize) { proconeline(); } } } proconeline() while @buffer && ($nextmatch || $prevmatch); sub proconeline { my $oldlinenum = $linenum - @buffer + 1; my $oldmatch = shift @matches; $_ = shift @buffer; if ($oldmatch || $oldlinenum - $prevmatch <= $after || $nextmatch) { print "$fname:" if $shownames; print "$oldlinenum:" if $showlines; print; } $prevmatch = $oldlinenum if $oldmatch; $nextmatch = 0 if $oldlinenum == $nextmatch; }
|
|---|