有如下日志:exmple.log
time: 1.236
operation:查询
time: 2.135
operation:处理
time: 3.741
operation:处理
time: 1.236
operation:查询
现在要求,统计出查询和处理以及其对应的平均时间
这个问题的关键点也是难点在于每两行是不可分割的部分。查了一下资料发现 xargs -l2能够使每两行合并为1行进行处理。故本问题的解法为:
cat example.log|xargs -l2|awk -F '\s' '{count[$3]++;time[$3]+=$2;}END{for(ind in count){print ind"\t"count[ind]"\t"time[ind]/count[ind]}}'
至此问题解决。
由于刚接触linux脚本,故写法肯定有很多不妥的地方,希望大家多多评论指导。
time: 1.236
operation:查询
time: 2.135
operation:处理
time: 3.741
operation:处理
time: 1.236
operation:查询
现在要求,统计出查询和处理以及其对应的平均时间
这个问题的关键点也是难点在于每两行是不可分割的部分。查了一下资料发现 xargs -l2能够使每两行合并为1行进行处理。故本问题的解法为:
cat example.log|xargs -l2|awk -F '\s' '{count[$3]++;time[$3]+=$2;}END{for(ind in count){print ind"\t"count[ind]"\t"time[ind]/count[ind]}}'
至此问题解决。
发现上面这个方法运行时间有些缓慢,在高人指点下学习了一下awk,后来改造该脚本为:
cat example.log|awk 'BEGIN{IGNORECASE=1}{if($0~/time:/){printf("%f\t",$2)}else if($0~/operation:/){printf("%s\n",$0)}}'|awk -F '/t' '{count[$3]++;time[$3]+=$2;}END{for(ind in count){print ind"\t"count[ind]"\t"time[ind]/count[ind]}}'
运行时间大大缩短。之所以使用cat,为了方便扩展,比如说只统计新增的日志,可以将cat example.log换成dd命令。
由于刚接触linux脚本,故写法肯定有很多不妥的地方,希望大家多多评论指导。