Linux中awk命令正確的求最大值、最小值、平均值、總和

工程師WWW發表於2016-09-13

test.txt檔案內容:
9
11
35
21
42
118


求最大值:

awk 'BEGIN {max = 0} {if ($1+0 > max+0) max=$1} END {print "Max=", max}' test.txt
Max= 118


求最小值:

awk 'BEGIN {min = 65536} {if ($1+0 < min+0) min=$1} END {print "Min=", min}' test.txt
Min= 9


求和:

cat test.txt|awk '{sum+=$1} END {print "Sum= ", sum}'
Sum=  236


求平均值:

cat test.txt|awk '{sum+=$1} END {print "Avg= ", sum/NR}'
Avg=  39.3333


求最大值(錯誤的求法):
cat test.txt|awk 'BEGIN {max = 0} {if ($1>max) max=$1 fi} END {print "Max=", max}'
Max= 9

求最小值(錯誤的求法):
cat test.txt|awk 'BEGIN{min = 65536}{if ($1<min) min=$1 fi}END{print "Min=", min}'
Min= 11

求最大值(正確的求法):
cat test.txt|awk 'BEGIN {max = 0} {if ($1+0>max+0) max=$1 fi} END {print "Max=", max}'
Max= 118

求最小值(正確的求法):
cat test.txt|awk 'BEGIN{min = 65536}{if ($1+0<min+0) min=$1 fi}END{print "Min=", min}'
Min= 9




awk預設按照字串比較的,如果要比較數值,需要先強制型別轉換,即 $1+0,轉換成整數。


Reference:

          http://xfeng.me/awk-get-max/

          http://www.ahlinux.com/shell/4072.html

          http://www.bkjia.com/LINUXxt/956509.html

相關文章