用awk如何制作csv

时间:2015-05-01 12:21:53

标签: csv awk

我有脚本输出,它给了我特定小时的例外数量。我希望make从数据中创建一个.csv文件。我想用awk或其他东西来做。

 44 17-04-15 21
 23 17-04-15 22
 15 17-04-15 23
  9 18-04-15 00
  8 18-04-15 01
  8 18-04-15 02
  9 18-04-15 03
 12 18-04-15 04
 11 18-04-15 05
  1 18-04-15 06
  2 18-04-15 09
  7 18-04-15 10
  7 18-04-15 11
 10 18-04-15 12

我希望得到以下结果

17-04-15,,,,,,,,,,,,,,,,,,,,,44,23,15
18-04-15,9,8,8,9,12,11,1,,,2,7,7,10

2 个答案:

答案 0 :(得分:2)

awk应该:

awk '{a[$2,($3+0)]=$1;b[$2];max[$2]=max[$2]<$3?$3:max[$2]} END {for (i in b) {printf i;for (j=0;j<=max[i];j++) printf ",%s",a[i,j];print ""}}' file
17-04-15,,,,,,,,,,,,,,,,,,,,,,44,23,15
18-04-15,9,8,8,9,12,11,1,,,2,7,7,10

答案 1 :(得分:1)

$ cat tst.awk        
$2!=prev { prtFlds(); flds[1]=$2 }
{ numFlds=$3+2; flds[numFlds]=$1 }
{ prev=$2 }
END { prtFlds() }
function prtFlds(       fldNr) {
    for (fldNr=1; fldNr<=numFlds; fldNr++) {
        printf "%s%s", flds[fldNr], (fldNr<numFlds?",":ORS)
    }
    delete flds
    numFlds = 0
}

$ awk -f tst.awk file
17-04-15,,,,,,,,,,,,,,,,,,,,,,44,23,15
18-04-15,9,8,8,9,12,11,1,,,2,7,7,10