awk maximum and minimum average sum

document content

# 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. Find the maximum id

Method One (Use preset values ​​for comparison)

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

 

Method two (use array sort to fetch the first value)

[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. Find the minimum id

Method One (Use preset values ​​for comparison)

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

  But this has a flaw: the minimum value must be given in advance, if you use $ 1 to obtain, the obtained value is empty

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

 

Method two (use array sort to fetch the first value)

[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. Take out the sum of id

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

  

4. Calculate the average value of id

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

 

Guess you like

Origin www.cnblogs.com/gentlemanhai/p/12745728.html