Quote:
Originally Posted by chrysler
There is a variant of problem about "Deleting empty line at end of text file in BASH".
If I want to reduce multiple continuous blank lines to just one blank line, how can I do? In other words, I don't want to eliminate just one blank line, but I want to reduce two or more continues blank lines to just one blank line. BTW, the blank lines might include space characters.
|
This will do it for completely blank lines (not if they contain spaces, however):
Code:
perl -00 -pe '' <file-name>
This will work even if there are spaces or tabs in one of the successive blank lines. (I'm sure that there are more elegant ways to do this second stage, but I'm tired, so this was the best I could do right now.)
Code:
#!/usr/bin/env perl
use strict;
use warnings;
my $blank;
while (<>) {
if (m/\S/) {
print;
$blank = 0;
}
elsif ($blank == 1) {
next;
}
else {
print;
$blank = 1;
}
}
Save it as, say, reducer and run it as
perl reducer <file-name>.
Edit: this Awk one-liner appears to work for all cases, so it's better.
Code:
awk 'NF { print $0 "\n" }' <file-name>
Edit 2: Now to round this out, here's the Perl one-liner that does what that very elegant Awk one-liner does. (I found the Awk one-liner
here.) Basically, it says, if I can split the line, print it and a newline. Otherwise, move on. It means, no more than one new line between lines with text. This does what you wanted. I'm leaving all the intermediate steps as a reminder to myself not to let go of things.
Code:
perl -nle 'print "$_\n" if split' <file-name>