perl -ne 'BEGIN{$re=qr/foo/}if(/$re/){print$p if$p!~/$re/;print$_};$p=$_' file