As far as I can tell none of the solutions here work. cat -s
as suggested by @DerMike isn't POSIX compliant (and it's less convenient if you're already using sed
for another transformation), and sed 'N;/^\n$/d;P;D'
as suggested by @Birei sometimes deletes more newlines than it should.
Instead, sed ':L;N;s/^\n$//;t L'
works. For POSIX compliance use sed -e :L -e N -e 's/^\n$//' -e 't L'
, since POSIX doesn't specify using ;
to separate commands.
Example:
$ S='foo\nbar\n\nbaz\n\n\nqux\n\n\n\nquxx\n';\
> paste <(printf "$S")\
> <(printf "$S" | sed -e 'N;/^\n$/d;P;D')\
> <(printf "$S" | sed -e ':L;N;s/^\n$//;t L')
foo foo foo
bar bar bar
baz baz baz
qux
qux
qux quxx
quxx
quxx
$
Here we can see the original file, @Birei's solution, and my solution side-by-side. @Birei's solution deletes all blank lines separating baz
and qux
, while my solution removes all but one as intended.
Explanation:
:L Create a new label called L.
N Read the next line into the current pattern space,
separated by an "embedded newline."
s/^\n$// Replace the pattern space with the empty pattern space,
corresponding to a single non-embedded newline in the output,
if the current pattern space only contains a single embedded newline,
indicating that a blank line was read into the pattern space by `N`
after a blank line had already been read from the input.
t L Branch to label L if the previous `s` command successfully
substituted text in the pattern space.
In effect, this deletes one recurrent blank line at a time, reading each into the pattern space as an embedded newline with N
and deleting them with s
.