perl -ne "m/foo/ and die @@ ; shift(@@) if push(@@,$_)>5" myfile.txt