Edgaras Alšauskas
Edgaras Alšauskas

Reputation: 87

Using awk to sum the values of a column, based on the values of another column

I am trying to sum up certain numbers in a column using awk. I would like to sum up numbers in second column with each other who has same IP adress.

2001:778:0:1::21 44
2001:778:0:1::21 1406
2001:778:0:1::21 66643
88.222.10.7 66643
88.222.10.7 1406
88.222.10.7 -
88.222.10.7 66643
88.222.10.7 1406
121.141.172.40 235
121.141.172.40 235

Desired output:

2001:778:0:1::21 68093
88.222.10.7 136098
121.141.172.40 470

Upvotes: 1

Views: 845

Answers (1)

RavinderSingh13
RavinderSingh13

Reputation: 133760

1st solution: Could you please try following.(in case you don't bother about sequence of 1st field in output)

awk '{a[$1]+=$NF} END{for(i in a){print i,a[i]}}'  Input_file

2nd solution: In case you want to keep order of 1st field same as Input_file's sequence then try following.

awk '!b[$1]++{c[++count]=$1} {a[$1]+=$NF} END{for(i=1;i<=count;i++){print c[i],a[c[i]]}}'  Input_file

Upvotes: 6

Related Questions