Calculate sum of column using reference of other column in awk

前端 未结 2 1313
误落风尘
误落风尘 2021-01-27 19:32

I have a file which contains 2 column. first column contains some keyword and second contains its size. Keywords can be repeated like below:

data1 5
data2 7
data         


        
2条回答
  •  無奈伤痛
    2021-01-27 20:06

    If you want to keep output in same order as the input then use this little longer awk:

    awk '$1 in a{a[$1]+=$2; next} {b[++k]=$1; a[$1]=$2}
                 END{for(i=1; i<=k; i++) print b[i], a[b[i]]}' file
    data1 8
    data2 21
    data3 4
    

提交回复
热议问题