perl -i.bak -nle"while ($empty) { --$empty; print '' } if (length()) { print } else { ++$empty }" filename #### foo CR LF bar CR LF CR LF CR LF #### foo CR LF bar CR LF