1

How can I find the summation for a certain field that is related to another field by awk, consider below sample:

File:

boo,foo,VO,1000
boo,foo,VO,1000
bar,var,DT,1000
var,bar,VO,2000

in this sample, I need to collect the number of $3 per $4, so the result would be:

VO,1000 2
DT,1000 1
VO,2000 1

were 1st and 2nd fields ignored.

3

If you don't mind reordering, the following should work

awk -F, '{print $3","$4}' <file name> | uniq -c

uniq -c counts the number of repetitions

For your input, the output is

  2 VO,1000
  1 DT,1000
  1 VO,2000

Further editing can be achieved via 2nd awk if required

  • 1
    Nice. Don't even need awk for this: cut -d, -f3,4 file | uniq -c – glenn jackman Oct 12 '15 at 16:44
  • What if I need to get the summation? if the $3 is a numeric value? – Eng7 Oct 13 '15 at 5:55
1

To do it all in awk:

awk '
    BEGIN {FS=SUBSEP=","} 
    {count[$3,$4]++} 
    END {for (key in count) print key, count[key]}
' file
DT,1000 1
VO,1000 2
VO,2000 1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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