awk统计最大值最小值

文件内容

# cat file 
id      appsSubmitted   appsCompleted   appsRunning     appsFailed      appsKilled      ts
5       95255   94881   8       77      289     2019-03-14 15:04:31
6       95263   94883   14      77      289     2019-03-14 15:06:08
7       95318   94941   11      77      289     2019-03-14 15:15:00
8       95318   94941   11      77      289     2019-03-14 15:15:01
9       95324   94947   11      77      289     2019-03-14 15:16:02
10      95326   94950   10      77      289     2019-03-14 15:17:01
11      95334   94955   13      77      289     2019-03-14 15:18:01
12      95337   94961   10      77      289     2019-03-14 15:19:01
13      95341   94966   9       77      289     2019-03-14 15:20:01
14      95341   94967   8       77      289     2019-03-14 15:21:02

  

1、求出最大id

方法一(利用预设值进行比对)

[root@hbhly_60_213 ~]# cat file |tail -n +2|awk -F " " 'BEGIN{max=0}{if($1>max){max=$1}}END{print max}' 
14

 

方法二(利用数组排序取出第一个值)

[root@hbhly_60_213 ~]# cat file |tail -n +2|awk -F " " '{number[$1]=$1}END{for(i in number){print number[i]|"sort -nr|head -n 1"}}'
14

  

2、求出最小id

方法一(利用预设值进行比对)

[root@hbhly_60_213 ~]# cat file |tail -n +2|awk -F " " 'BEGIN{min=5}{if($1<min){min=$1}}END{print min}'                                  
5

  但是这个有个缺陷:最小值必须提前给出,如果用$1来获取,获取的值是空

[root@hbhly_60_213 ~]# cat file |tail -n +2|awk -F " " 'BEGIN{min=$1}{if($1<min){min=$1}}END{print min}'   

 

方法二(利用数组排序取出第一个值)

[root@hbhly_60_213 ~]# cat file |tail -n +2|awk -F " " '{number[$1]=$1}END{for(i in number){print number[i]|"sort -n|head -n 1"}}' 
5

  

3、取出id的总和

[root@hbhly_60_213 ~]# cat file |tail -n +2|awk -F " " '{sum+=$1}END{print sum}'                              
95

  

4、算出id的平均值

[root@hbhly_60_213 ~]# cat file |tail -n +2|awk -F " " '{sum+=$1}END{print sum/(NR-1)}'
10.5556

 

posted on 2020-04-21 16:51  gentleman_hai  阅读(1859)  评论(0编辑  收藏  举报

导航