perl -ne '$a[($i+=1)%=5] = $_ if /foo/; END{print @a[$i+1..@a,0..$i]}' file