use strict; use warnings; use Tie::File; use Getopt::Std; our %opts; getopt('AB',\%opts); die "USAGE: $0 [-An] [-Bn] match file" unless @ARGV; my ($match,$filename) = @ARGV; my @file; tie @file, 'Tie::File', $filename; # i wish there was a way for grep to return indices ... my @found; for (0..$#file) { push @found, $_ if $file[$_] =~ /$match/; } for (@found) { my ($start,$end) = ($_,$_); $start -= $opts{A} if $opts{A}; $end += $opts{B} if $opts{B}; $start = 0 if $start < 0; $end = $#file if $end > $#file; print $_,$/ for @file[$start..$end]; }