如何在awk中使用计数器

时间:2014-03-02 08:22:14

标签: arrays unix if-statement awk

我有这个输入例如

jak   101 98   
jon   101 97 
aiden 102 81
sam   105 77 
bob   106 55  
jo    102 96  
mik   103 91  
hanna 125 20  
mode  102 49  
anna  101 82 
...
..
.
.

。对于1200名学生(我需要的是101..102..103的数量和10名毕业生最多的学生

看起来像这样

101 have :3 student the higher score is  jak ==98,jon==97,aiden==81    (but i need to most 10  ) ...........
102 have :2 student the higher score is  81,49
103 have :1 student the higher score is  91
105 have :1 student the higher score is 77
106 have :1 student the higher score is 55 
125 have :1 student the higher score is 20

1 个答案:

答案 0 :(得分:2)

这应该有效:

awk 'count[$2]++<10 { 
    stats[$2]=(stats[$2])?stats[$2]","$3:$3
}
END {
    for(x in count) {
        printf "%d have :%d student the higher score is %s\n",x,count[x],stats[x]
    }
}' file

输出:

$ cat file
jak   101 98   
jon   101 97 
aiden 102 81
sam   105 77 
bob   106 55  
jo    102 96  
mik   103 91  
hanna 125 20  
mode  102 49  
anna  101 82

$ awk 'count[$2]++<10 { 
    stats[$2]=(stats[$2])?stats[$2]","$3:$3
}
END {
    for(x in count) {
        printf "%d have :%d student the higher score is %s\n",x,count[x],stats[x]
    }
}' file
101 have :3 student the higher score is 98,97,82
102 have :3 student the higher score is 81,96,49
103 have :1 student the higher score is 91
105 have :1 student the higher score is 77
106 have :1 student the higher score is 55
125 have :1 student the higher score is 20

更新

要包含学生姓名,请使用以下内容:

awk 'count[$2]++<10 { 
    stats[$2]=(stats[$2])?stats[$2]","$1"="$3:$1"="$3
}
END {
    for(x in count) {
        printf "%d have :%d student the higher score is %s\n",x,count[x],stats[x]
    }
}' file

输出:

$ awk 'count[$2]++<10 { 
    stats[$2]=(stats[$2])?stats[$2]","$1"="$3:$1"="$3
}
END {
    for(x in count) {
        printf "%d have :%d student the higher score is %s\n",x,count[x],stats[x]
    }
}' file
101 have :3 student the higher score is jak=98,jon=97,anna=82
102 have :3 student the higher score is aiden=81,jo=96,mode=49
103 have :1 student the higher score is mik=91
105 have :1 student the higher score is sam=77
106 have :1 student the higher score is bob=55
125 have :1 student the higher score is hanna=20