$/ = undef; open FILE, '<', $_; my $file = ; $/ = "\n"; close FILE; my @matches = $file =~ /((?:.*\n?){$lines_up}) (.*$pattern.*\n?) ((?:.*\n?){$lines_down})/x; my @parts = qw(lines_up matched_line lines_down); for (@matches) { if (! (my $index = $run++ % 3)) { print "match #" . (int($run / 3) + 1) . " in file\n"; } print $parts[$index] . ":\n$_\n"; }