perl -ne 'print @t if /foo/; @t=(@t[1..4],$_)' file