views:

39

answers:

3
+2  Q: 

scripting in awk

I have a text file with contents as below:

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

i need the output as :

A,300
B,500

the logic here is sum of all the 3rd fields whose 2nd field is A and in the same way for B

how could we do it using awk?

+2  A: 

You can do it using a hash as:

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

Well, I'm not up for writing and debugging the code for you. However, the elements you need are:

  • You can use FS="," to change the field separator to a comma.
  • The fields you care about are obviously the second ($2) and third ($3) fields.
  • You can create your own variables to accumulate the values into.
T.E.D.
A: 
$ awk -F"," '{_[$2]+=$3}END{for(i in _)print i,_[i]}' OFS="," file
A,300
B,500
ghostdog74