Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

I have a file of the form

VL-8299673,30.000,49.000,1.000,21.901,2630.000,428861.000
VL-8299673,1071.000,570.000,35.000,3963.608,632.000,366563.000
VL-8299673,36.000,867.000,24.000,6523.005,3544.000,176054.000
VL-8299673,5:281185.000
VL-8299673,44.000,372.000,67.000,7029.358,293.000,446448.000
VL-8299673,5:48479.000
VL-8299673,0:2.000,2:7.000,3:80.222,4:1153.000

it is supposed to be of the form

VL-8299673,1190.000,609.000,28.000,12676.158,1819.000,452813.000

but when there are zeros in the file it only shows the column numbers that are nonzero such as

VL-8299673,0:2.000,2:7.000,3:80.222,4:1153.000

I would like to write a sed command that makes a 7 length row with zeros included such as

VL-8299673,2.000,0,7.000,80.222,1153.000,0

Any ideas?

share|improve this question
1  
Why sed and not awk (or perl or python or ...)? –  Johnsyweb Feb 6 '13 at 21:47
2  
Woaw! Once again someone reinvented the wheel and now craig, you are screwed :) I don't know from where your file comes from, but you'd better change the program generating that crap to make it generate proper csv. Plus, I guess that you won't just keep the csv somewhere forever: you will process it using whatever you want and if "whatever" is not gnuplot or libreoffice calc, you'd better use this whatever directly to parse that broken format. Oh, one last thing: if the guy who wrote the program really wanted to save space, he would just have zipped it or used a binary format (such as HDF5). –  user21228 Feb 7 '13 at 9:37

1 Answer 1

Though it could be done with sed, it would be a lot more legible with perl ;-):

perl -lpe '$n=0;s{,(\d+:)?([^,]*)}{if($1ne""){$r=",0"x($1-$n).",$2";
           $n=$1}else{$r=$&};$n++;$r}ge;$_.=",0"x(6-$n)'

A possible sed solution (not much tested):

sed 's/$/%543210@@@@@@@/;:1
  s/^\(\(@*\)[^,]*\),\([0-9]\):\(.*%.*\3.\{6\}\2\(.*\)\)/\5\1\5\4/;t1
  s/^\([^:]*\),/@\1@/;t1
  s/@*\(.*\)%.*/\1@@@@@@@/;s/\(\(@[^@]*\)\{7\}\).*/\1/
  :2
  s/@@/,0@/;t2
  y/@/,/;s/,$//'
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.