红联Linux门户
Linux帮助

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

发布时间:2016-08-03 12:14:02来源:linux网站作者:寜靜致遠
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
 
Linux中awk命令正确的求最大值、最小值、平均值、总和
 
awk默认按照字符串比较的,如果要比较数值,需要先强制类型转换,即 $1+0,转换成整数。
 
本文永久更新地址:http://www.linuxdiyf.com/linux/22954.html