mario
mario

Reputation: 55

using awk how to make csv

I have output from script which gives me number of exceptions in particular hour. I want make to make a .csv file from data. and I think to use awk or something else to do it.

 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

I expect to get the following result

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

Upvotes: 0

Views: 69

Answers (2)

Ed Morton
Ed Morton

Reputation: 203483

$ 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

Upvotes: 1

Jotne
Jotne

Reputation: 41456

This awk should do:

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

Upvotes: 2

Related Questions