Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sed to combine N text lines separated by blank lines?

Tags:

sed

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.

like image 955
Leslie Avatar asked Sep 27 '16 20:09

Leslie


2 Answers

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.

like image 195
potong Avatar answered Oct 25 '22 07:10

potong


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 processing
  • tr/\n/ /' changes all newlines to spaces
like image 37
glenn jackman Avatar answered Oct 25 '22 05:10

glenn jackman