Vijay
Vijay

Reputation: 67221

awk command which is not working as expected

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

Answers (3)

ghostdog74
ghostdog74

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

Flash
Flash

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

Neo
Neo

Reputation: 5463

Try:

awk -F, '{arr[$2]+=$1}END{for(i in arr)print i,",",arr[i]}'

Upvotes: 1

Related Questions