open(FILE, 'file') || die("Yaroo!\n"); my $N = 3; # 3 lines above and below my $target = 'stuff what you want'; my @window = ('') x ($N + $N + 1); while() { shift @window; push @window, $_; print @window, "\n\n" if($window[$N] =~ /$target/); } foreach(1 .. $N) { shift @window; print @window, "\n\n" if($window[$N] =~ /$target/); }