9

[笔记] awk命令计算sum, min, max, avg

 3 years ago
source link: https://blog.csdn.net/yanxiangtianji/article/details/78014882
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

[笔记] awk命令计算sum, min, max, avg

original.png
yanxiangtianji 2017-09-18 00:10:13 articleReadEyes.png 1544
awk 'BEGIN{max=0;min=9e9}{FS=" "}{x+=$5;if($5>max){max=$5}else if($5<min){min=$5}}END{print x,"\t",max,"\t",min,"\t",x/NR}'

讲解:
1. FS指定间隔符 (每一段用$x引用,编号从1开始)
2. BEGIN和END后面为一次性命令,中间的主体部分对每一行执行
3. 类似c语法,各段使用{}包裹,语句使用;分隔
4. NR为number of records,即行数,NF为number of fields,即当前行被分割了多少段,FNR为file number of records,即当前文件内的行数;$NF表示最后一个field的

上面代码分解为:

awk 'BEGIN{max=0;min=9e9}
{FS=" "}
{
    x+=$5;
    if($5>max){max=$5}
    else if($5<min){min=$5}
}
END{print x,"\t",max,"\t",min,"\t",x/NR}'

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK