Awk scripts

I have a text file with content as shown below:

1,A,100
2,A,200
3,B,150
4,B,100
5,B,250

      

I need output as:

A,300
B,500

      

the logic here is the sum of all 3 fields, the second field of which is A and in the same way for B

how can we do this with awk?

+2


a source to share


3 answers


You can do it using hash

like:



awk -F"," '{cnt[$2]+=$3}END{for (x in cnt){printf "%s,%d\n",x,cnt[x]}}' file

      

+2


a source


Well, I'm not going to write and debug the code for you. However, the required items are:



+1


a source


$ awk -F"," '{_[$2]+=$3}END{for(i in _)print i,_[i]}' OFS="," file
A,300
B,500

      

0


a source







All Articles