0

I have a text file that looks like this:

A 500 100 ABC
B 200 100 BBB
B 200 100 ACC
D 150 235 CDD
A 500 100 RER
C 210 653 DDD
C 210 653 DWR
D 150 653 DDW
D 150 653 DER

What I try to accomplish is to filter out the first for unique names and get a total of all of the value behind it (sum of column 2 and 3) eg:

A 1000 200
B 400 200

I got it sort of working for the first 2 with the following awk line:

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

That results in:

A 1000
B 400

I'm stuck on adding the 3th column in the mix. Does anyone have the tip for adding column 3?

closed as off-topic by Jeff Schaller, Jakuje, user79743, Wildcard, Thomas Dickey Mar 30 '16 at 1:29

This question appears to be off-topic. The users who voted to close gave this specific reason:

  • "Questions describing a problem that can't be reproduced and seemingly went away on its own (or went away when a typo was fixed) are off-topic as they are unlikely to help future readers." – Jeff Schaller, Jakuje, Community, Wildcard, Thomas Dickey
If this question can be reworded to fit the rules in the help center, please edit the question.

  • 1
    hint: b[$1] += $3 – iruvar Mar 29 '16 at 19:47
  • ha... I actually tried that, but without ; Works now.. Thanks! – CharNL Mar 29 '16 at 19:56
2

Give this tested version a try:

awk '{ colone[$1]+=$2; coltwo[$1]+=$3; } END { for (i in colone) { print i " " colone[i] " " coltwo[i]; }}' file

It is using associative arrays, see the famous tutorial Awk - A Tutorial and Introduction - by Bruce Barnett

The test is below:

awk '{ colone[$1]+=$2; coltwo[$1]+=$3; } END { for (i in colone) { print i " " colone[i] " " coltwo[i]; }}' file
A 1000 200 
B 400 200
C 420 1306
D 450 1541

Not the answer you're looking for? Browse other questions tagged or ask your own question.