I searched a bit, but didn't find a solution for this specific situation. Given a pipe that outputs groups of an arbitrary number of non-blank lines separated single blank lines, is there a sed one-liner (or awk one-liner or perl one-liner) that will combine the groups of non-blank lines into single lines, while preserving the blank lines? For example, the input
one
two
three
four
five
six
seven
eight
should be output as
one two
three four five
six
seven eight
Thanks in advance to all who respond.
This might work for you (GNU sed):
sed '/./{:a;N;s/\n\(.\)/ \1/;ta}' file
If the line is not empty read the following line and if that is not empty replace the newline by a space and repeat, otherwise print the pattern space. If the line was empty in the first place print the empty line: this caters for an empty first line, if this is not the case then and there is only one empty line between non-blank lines:
sed ':a;N;s/\n\(.\)/ \1/;ta' file
is suffice.
Perl one-liner
perl -00 -lpe 'tr/\n/ /'
where
-00
reads the input in blank-line-separated paragraphs-l
automatically handles end-of-line newlines-p
automatically prints each record after processingtr/\n/ /'
changes all newlines to spacesIf you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With