如何编写shell脚本以从sar报告中查找ram利用率的最小值和平均值

时间:2017-11-03 13:24:13

标签: linux bash shell awk

我编写了一个shell脚本,用于从命令sar -r -f的sar报告中查找avg,min和max值,如下所示

MIN1=`sar -r -f |awk '{print $5}'|grep -v '%memused'|awk 'min=="" || $0 < min {min=$0} END{ print min}'`

MAX1=`sar -r -f |awk '{print $5}'|grep -v '%memused'|grep -v '_x86_64_'|grep -v '86327'|awk 'min=="" || $0 > min {min=$0} END{ print min}'`

AVG1=`sar -r -f |awk '{print $5}'|grep -v '%memused'|grep -v '_x86_64_'|grep -v '86327'|awk '{total+=$0} END {print total/NR}'`

echo Minimum value is $MIN1 : average value is $AVG1 : maximum value is $MAX1

sar -r -f命令o / p:

Linux 2.6.32-431.el6.x86_64 (servername)   11/03/2017      _x86_64_        (4 CPU)

12:00:01 AM kbmemfree kbmemused  %memused kbbuffers  kbcached  kbcommit   %commit

Average:       315191  32697953     99.05     86327  16937751  25889218     53.25

脚本输出:

Minimum value is 95.50 : average value is 868.053 : maximum value is 86327

预期输出:

Minimum value is 95 : average value is 96 : maximum value is 97

我已使用grep -v 86327中的{{ execution_date }}跳过该值,但每次输出变化时它都会变化。

1 个答案:

答案 0 :(得分:0)

关注单awk可能对您有帮助。

sar -r -f |  awk '
FNR>1&&!/memused/{
 max=max>$5?max:$5;
 min=min>$5?$5:(min?min:$5);
 sum+=$5}
END{
print "Minimum:",min,"Average:",(sum/FNR),"Maximum:",max
}'

编辑: 现在也为代码添加说明。

sar -r -f |  awk '      ## Sending sar standard output as a standard input by pipe to awk command.
FNR>1&&!/memused/{      ## checking if line number is greater than and not having string memused in it then do following.
 max=max>$5?max:$5;     ## creating a variable named max and checking if max variable value is greater than 5th field then keep it as max else keep it as 5th field to get the maximum values.
 min=min>$5?$5:(min?min:$5); ##creating a variable named min and checking if min value is greater than 5th field if yes then change its value to $5 or check if min is there keep its value to min or if min is NULL then keep it as $5 value.
 sum+=$5}               ## creating variable named sum and adding its value to itself along with 5th fields value.
END{
print "Minimum:",min,"Average:",(sum/FNR),"Maximum:",max ##Printing string minimum and min value similarly with avg and maximum too.
}'