my $match = 0; while () { # get rid of newlines chomp; if ($match){ # we have a line to print; reset the counter $match = 0; # replace multi-spaces with a single one s/\s+/ /g; print NEW "$_\n"; } if (/$find/){ # we found a $find; set $match to true $match = 1; print NEW $_; } }