awk的学习和使用(二)
上一篇 /
下一篇 2009-08-14 21:08:20
/ 个人分类:Linux
举例, test文本,内容如下,三列分别表示:电话号码、通话时间、费用。
13911025243 1 3 13911125274 2 6 13911025243 3 6 13810025274 3 6 13911025243 2 6 |
将以上文本中,每个电话号码的总通话时间、总费用进行统计;
1.先排序:sort test
2.将第一条记录的三个字段均保存到自定义变量,分别为:phoneNum=$1;time=$2;cost=$3;
3.此后没读取一条记录时,$1,$2,$3与phonenum,time,cost作比较,如果phoneNum相等,则time=time+$2;cost=cost+$3;如果不相等,就打印phonenum,time,cost,并重置自定义变量值为:phoneNum=$1;time=$2;cost=$3;
4.最后,需要在end里打印最后一次统计信息;
实现如下:
sort test | awk '{if(NR==1){phoneNum=$1;time=$2;cost=$3}else if($1==phoneNum){time+=$2;cost+=$3}else{print (phoneNum,time,cost);phoneNum=$1;time=$2;cost=$3;}}END{print phoneNum,time,cost}' |
收藏
举报
TAG: