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