Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count value in column by hours and add header

Tags:

awk

In column 3 the value is hour, I will like to print the header from 0 to 23 hrs and count in column 3 the times repeated by hr. If not value for hr is found then print 0.

Input file

123 3 3
122 3 3
122 4 4
122 3 4
122 4 4
122 5 5
122 3 12
122 4 15
122 5 20
122 5 20

Output desired

First row = Header 0 to 23 hrs separated by,

Second row = Values found for each hr., If not value is found print 0.

0,1,2,3,4,5,6,7,8,9,10,11,12,13,15,16,17,18,19,20,21,22,23
0,0,0,2,3,1,0,0,0,0,0,0,1,0,0,1,0,0,0,0,2,0,0,0

To count by hr, I tried

awk '{a[$3]++} END {for(i in a) print i, a[i]}'

Thanks in advance.

like image 481
OXXO Avatar asked Nov 19 '25 12:11

OXXO


1 Answers

another awk

$ awk '{a[$3]++} 
    END{while(i<24) 
          {h1=h1 s i+0; 
           h2=h2 s a[i++]+0; 
           s=","} 
        print h1 ORS h2}' file

0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23
0,0,0,2,3,1,0,0,0,0,0,0,1,0,0,1,0,0,0,0,2,0,0,0

ps. looks like a variation of @JamesBrown's answer.

like image 90
karakfa Avatar answered Nov 21 '25 09:11

karakfa



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!