Joining lines in TXT file based on first character

Hi,

I have a pipe delimeted text file where lines have been split over 2 lines and I need to join them back together. For example the file I have is similar to the following:

aaa|bbb
|ccc
ddd|eee
fff|ggg
|hhh

I ideally need to have it looking like the following

aaa|bbb|ccc
ddd|eee
fff|ggg|hhh

I just dont seem to be able to get exactly what I need!

Any help would be very much appreciated.

Cheers,

try:

awk '{for(i=1; i<=NF; i++) if ($i !~ /^[|]/) {printf ($(i+1) !~ /^[|]/) ? $i "\n" : $i } else {print $i} }' RS= input

Rather than write masses of shell script in a while read line loop, a pretty crummy way with vi might do the job:-

count=`grep -c "^|" $file`
i=1
( while [ $i -le $count ]
do
   echo "/^|kJ\c"
done
echo ":wq" ) | vi $file

I suspect a properly written awk or sed would be much better.

Robin

---------- Post updated at 03:51 PM ---------- Previous update was at 03:50 PM ----------

:o Ah, there's one on the thread already. :o

Another awk veresion

awk '{s=(a!~/^\|/ && $0!~/^\|/)?"":"\n";printf "%s"s,$0;a=$0}' file
aaa|bbb|ccc
ddd|eee
fff|ggg|hhh

A portable solution that joins any number of lines beginning with | is

sed -e ':a' -e '$b' -e 'N; s/\n|/|/; ta' -e 'P;D' file
awk '{printf (/^\|/)?$0:RS $0}' infile
1 Like