简体   繁体   中英

shellscript and awk extraction to calculate averages

I have a shell script that contains a loop. This loop is calling another script. The output of each run of the loop is appended inside a file (outOfLoop.tr). when the loop is finished, awk command should calculate the average of specific columns and append the results to another file(fin.tr). At the end, the (fin.tr) is printed.

I managed to get the first part which is appending the results from the loop into (outOfLoop.tr) file. also, my awk commands seem to work... But I'm not getting the final expected output in terms of format. I think I'm missing something. Here is my try:

#!/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

I want the format to be like :

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

I have incremented max inside the awk command by 0.5 as there was new line between the out put of the results (output of outOfLoop file)

$ 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM