perl -ne 'print @t if /foo/; push @t,$_; shift @t if $#t>5' file