Best way to simulate “group by” from bash?

前端 未结 14 1085
半阙折子戏
半阙折子戏 2020-11-29 15:03

Suppose you have a file that contains IP addresses, one address in each line:

10.0.10.1
10.0.10.1
10.0.10.3
10.0.10.2
10.0.10.1

You need a

14条回答
  •  难免孤独
    2020-11-29 15:57

    for summing up multiple fields, based on a group of existing fields, use the example below : ( replace the $1, $2, $3, $4 according to your requirements )

    cat file
    
    US|A|1000|2000
    US|B|1000|2000
    US|C|1000|2000
    UK|1|1000|2000
    UK|1|1000|2000
    UK|1|1000|2000
    
    awk 'BEGIN { FS=OFS=SUBSEP="|"}{arr[$1,$2]+=$3+$4 }END {for (i in arr) print i,arr[i]}' file
    
    US|A|3000
    US|B|3000
    US|C|3000
    UK|1|9000
    

提交回复
热议问题