Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

I'm searching for a way to solve this problem in awk. Input:

X 1
Y 2
Z 3
X 4
Y 5

The output should look like this:

X 5
Y 7
Z 3

I see two problems here: the first one is the indirect reference in awk. Is it even possible?
It would work this way: if $$1 (X) exists add $2 else declare $$1 (X) then add $2
Even if I would figure out how to do it I would still need to know the name of all the declared variables i.e. X,Y,Z.

I'm guessing there is a simpler way to handle this task but I can't figure it out...

share|improve this question
add comment

1 Answer

up vote 7 down vote accepted

In awk array are associative, so the following works:

awk '{ vect[$1] += $2 }; 
 END { for (item in vect) print item, vect[item] }' input-file
share|improve this answer
    
This is exactly what I was looking for. Thanks! –  Cid Oct 3 '11 at 11:42
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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