How can I sum values in column based on the value in another column?

Sam picture Sam · Feb 22, 2010 · Viewed 11.3k times · Source

I have a text file which is:

ABC 50
DEF 70
XYZ 20
DEF 100
MNP 60
ABC 30

I want an output which sums up individual values and shows them as a result. For example, total of all ABC values in the file are (50 + 30 = 80) and DEF is (100 + 70 = 170). So the output should sum up all unique 1st column names as -

ABC 80
DEF 170
XYZ 20
MNP 60

Any help will be greatly appreciated.

Thanks

Answer

ghostdog74 picture ghostdog74 · Feb 22, 2010
$ awk '{a[$1]+=$2}END{for(i in a) print i,a[i]}' file
ABC 80
XYZ 20
MNP 60
DEF 170