Text Processing – Concatenate Lines Based on First Character of Next Line

awkperlsedtext processing

I am looking for away contact lines based on the next line. So far the only way I see is to create a shell script that will read line by line and will do something along these lines:

while read line
    if $line does not start with "," and $curr_line is empty 
        store line in curr_line
    if $line does not start with "," and $curr_line is not empty
        flush $curr_line to file
        store $line in $curr_line
    if $line starts with "," append to $curr_file, flush to file empty curr_line
done < file

So I am trying to understand if could be achieved with sed or even grep with redirection.
the rules of the file are simple.
There is at max one and only one line starting with "," that needs to be appended to the previous line.

ex:

line0
line1
line2
,line3
line4
line5
,line6
line7
,line8
line9
line10
line11

The result file would be

line0
line1
line2,line3
line4
line5,line6
line7,line8
line9
line10
line11

Best Answer

I'd do:

awk -v ORS= '
  NR>1 && !/,/ {print "\n"}
  {print}
  END {if (NR) print "\n"}' < file

That is, only prints that newline character that delimits the previous line if the current one does not start with a ,.

In any case, I wouldn't use a while read loop.

Related Question