2013-05-10 79 views
-1

我有一個包含循環的shell腳本。這個循環正在調用另一個腳本。循環的每次運行的輸出都附加在文件(outOfLoop.tr)中。當循環結束時,awk命令應計算特定列的平均值並將結果附加到另一個文件(fin.tr)。最後,打印(fin.tr)。shellscript和awk提取來計算平均值

我設法得到第一部分,將循環結果附加到(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 

我已經0.5遞增max awk命令裏面,因爲是出把結果之間的新生產線( outOfLoop文件的輸出)

+0

你爲什麼不在[tag:awk]中做所有事情? – Johnsyweb 2013-05-10 03:39:15

+0

我的問題不是來自shell腳本。這是從awk格式化的!!如果我在awk中完成整個...問題仍然沒有解決! – SimpleNEasy 2013-05-10 03:53:13

+1

在awk中編寫整個東西並不能保證解決你的問題,但是如果你有這個問題,它會讓你不太可能首先遇到問題,而且更容易解決問題。 – 2013-05-10 04:00:15

回答

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 
+0

謝謝...代碼完美..但是,'A'值不會被打印出來。不知道爲什麼? – SimpleNEasy 2013-05-10 04:46:37

+0

解決了「A」值丟失的問題。查看更新。 – SimpleNEasy 2013-05-10 05:12:24

+0

有趣。大多數現代的awks會「記住」最後一個記錄讀取的值,所以你可以在END部分直接訪問它,所以通常你可以像END一樣在END部分使用$ 1,它會引用第一個字段最後一條記錄的讀取。您可能想要考慮爲此獲取GNU awk以及許多更有用的功能。 – 2013-05-10 05:27:30