# put the line into the cache/queue; shorten the array if it's more than we want; print the array if current line mataches. perl -ne 'push @lines, $_; shift @lines if scalar(@lines)>4; print join "", @lines if /foo/' file # if you don't want the current line printed as one of the 4, just rearrange a little: perl -ne 'print join "", @lines if /foo/; push @lines, $_; shift @lines if scalar(@lines)>4' file