awk 分組求和

awk 分組求和

分組求和
awk  '{s[substr($2,1,6)] += $1} END{for(i in s) {print i, s[i]/(1024*1024*1024)} }' file_to_read.txt |sort -n

這裏面用到了awk的知識和字典的知識。AWK 中須要瞭解的就是$N 表明所讀取內容的第N 列。css

可能有人對字典不太瞭解. s={'name':'halberd'} ,這就是一個字典,是Key-value的組合。html

在上面的字典示例中,key 是 'name',value 是 'halberd'。s[name] 的值 就是 'halberd'。java

返回上面的AWK示例, s[substr($2,1,6)] += $1 表明把文件 file_to_read.txt 每行中第二列的前6個字符做爲 字典 s 的key 。python

當substr($2,1,6) 的值第一次出現時,s[substr($2,1,6)] = $1。 sql

當substr($2,1,6) 的值重複出現時時, s[substr($2,1,6)] += $1 表明,把$1 的值 加到 原來s[substr($2,1,6)]上,也就是s[substr($2,1,6)] = s[substr($2,1,6)] + $1。經過字典的管理方式,進行數據的求和。shell

file_to_read.txt 部份內容以下:sass

.........
1125017 20180820174000
277 20180820174000
1491471 20180820175000
663 20180820175000
1429371 20180920170000
3716506 20181020170000
21055029 20181020170000
2218546 20181020171000
4650637 20181020174000
23847465 20181020174000
5341238 20181020175000
24666314 20181020175000
1621883 20181120170000
20620952 20181120170000
1756716 20181120171000
21409188 20181120171000
23085774 20190920174000
1126625 20190920175000
24564610 20190920175000
583910 20191020170000
22511935 20191020170000
921893 20191020171000
23906308 20191020171000
629943 20191020172000
25916302 20191020172000
1063984 20191020173000
25617169 20191020173000
780478 20191020174000
................
結果示例
201808 2.50172
201809 6.61726
201810 66.528
201811 84.6913
201812 91.871
201901 115.439
201902 124.768
201903 115.127
201904 91.7492
201905 93.8242
201906 92.1708
201907 83.1374
201908 95.1076
201909 85.789
201910 80.9189

Author: halberd.leeruby

Created: 2019-10-28 Mon 17:30bash

Validatebabel

相關文章
相關標籤/搜索