Reputation: 67221
I have a file input as below:
-4.0,vijay
-2.0,chan
-3.0,vijay
and my command is :
awk -F, '{a[$2]=a[$2]+$1}{for (i in a) print i","a[i]}'
i am expecting
vijay,-7.0
chan,-2.0
the actual output is
vijay -4
vijay -4
chan -2
vijay -7
chan -2
Upvotes: 1
Views: 199
Reputation: 342363
You need to print the array at the END block otherwise your for loop will start to print for each record iterated.
awk -F, '{a[$2]+=$1}END{for (i in a) print i","a[i]}' file
Upvotes: 0
Reputation: 16703
Looks like you need to save the print until all the lines have been processed.
'{a[$2]=a[$2]+$1}END{for (i in a) print i","a[i]}'
Also try printf
to get the comma in the right spot.
Upvotes: 1