shell脚本和awk提取来计算平均值

时间:2013-05-10 03:31:18

标签: shell awk

我有一个包含循环的shell脚本。这个循环正在调用另一个脚本。循环的每次运行的输出都附加在文件(outOfLoop.tr)中。当循环结束时,awk命令应计算特定列的平均值,并将结果附加到另一个文件(fin.tr)。最后,打印出(fin.tr)。

我设法得到第一部分,将循环结果附加到(outOfLoop.tr)文件中。另外,我的awk命令似乎有用...但是我没有得到格式方面的最终预期输出。我想我错过了什么。这是我的尝试:

#!/bin/bash

rm outOfLoop.tr
rm fin.tr

x=1
lmax=4

while [ $x -le $lmax ]

do
calling another script >> outOfLoop.tr
x=$(( $x + 1 ))
done
cat outOfLoop.tr
#/////////////////
#//I'm getting the above part correctly and the output is :
27 194 119 59 178

27 180 100 30 187

27 175 120 59 130

27 189 125 80 145
#////////////////////
#back again to the script

echo "noRun\t A\t B\t C\t D\t E"
echo "----------------------\n"

#// print the total number of runs from the loop 
echo "$lmax\t">>fin.tr

#// extract the first column from the output which is 27
awk '{print $1}' outOfLoop.tr  >>fin.tr
echo "\t">>fin.tr


#Sum the column---calculate average
awk '{s+=$5;max+=0.5}END{print s/max}' outOfLoop.tr  >>fin.tr
echo "\t">>fin.tr


awk '{s+=$4;max+=0.5}END{print s/max}' outOfLoop.tr  >>fin.tr
echo "\t">>fin.tr

awk '{s+=$3;max+=0.5}END{print s/max}' outOfLoop.tr  >>fin.tr
echo "\t">>fin.tr


awk '{s+=$2;max+=0.5}END{print s/max}' outOfLoop.tr  >> fin.tr
echo "-------------------------------------------\n" 


cat fin.tr
rm outOfLoop.tr

我希望格式如下:

noRun    A       B           C            D         E
----------------------------------------------------------
4        27      average    average      average   average

我已经将awk命令中的max增加了0.5,因为结果输出之间有一条新行(outOfLoop文件的输出)

1 个答案:

答案 0 :(得分:2)

$ cat file
27 194 119 59 178

27 180 100 30 187

27 175 120 59 130

27 189 125 80 145

$ cat tst.awk
NF {
    for (i=1;i<=NF;i++) {
        sum[i] += $i
    }
    noRun++
}
END {
    fmt="%-10s%-10s%-10s%-10s%-10s%-10s\n"
    printf fmt,"noRun","A","B","C","D","E"
    printf "----------------------------------------------------------\n"
    printf fmt,noRun,$1,sum[2]/noRun,sum[3]/noRun,sum[4]/noRun,sum[5]/noRun
}

$ awk -f tst.awk file
noRun     A         B         C         D         E
----------------------------------------------------------
4         27        184.5     116       57        160