[英]Arithmetic calculation in shell scripting-bash
我有一個輸入記事本文件,如下所示:
樣本輸入文件:
蔬菜和費率
kg rate total
Tomato 4 50 100
potato 2 60 120
Beans 3 80 240
總數:(100 + 120 ++ 240)= 460
我需要將第2列和第3列相乘,並檢查總數是否正確以及總數。 如果不正確,我們需要在同一文件中打印一條錯誤消息,如下所示
在這里輸入代碼
樣本輸出文件:
蔬菜和費率
kg rate vegtotal
Tomato 4 50 200
potato 2 60 120
Beans 3 80 240
總數:(200 + 120 ++ 240)= 560
計算錯誤:西紅柿的蔬菜錯誤:應該是200而不是100總體錯誤:應該是560而不是460
到目前為止的代碼:
for f in Date*.log; do
awk 'NR>1{ a[$1]=$2*$3 }{ print }END{ printf("\n");
for(i in a)
{ if(a[i]!=$4)
{ print i,"Error in calculations",a[i] }
} }' "$f" > tmpfile && mv tmpfile "$f";
done
它計算總計,但不比較值。 如何比較它們並打印到同一文件?
復雜的awk解決方案:
awk 'NF && NR>1 && $0!~/total:/{
r=$2*$3; v=(v!="")? v"+"r : r;
if(r!=$4){ veg_er[$1]=r" instead of "$4 }
err_t+=$4; t+=r; $4=r
}
$0~/total/ && err_t {
print $1,"("v")",$3,t; print "Error in calculations:";
for(i in veg_er) { print "Veg total for "i" is wrong: it should be "veg_er[i] }
print "Overalltotal is wrong: It should be "t" instead of "err_t; next
}1' inputfile
輸出:
kg rate total
Tomato 4 50 200
potato 2 60 120
Beans 3 80 240
Overalltotal: (200+120+240) = 560
Error in calculations:
Veg total for Tomato is wrong: it should be 200 instead of 100
Overalltotal is wrong: It should be 560 instead of 460
細節:
NF && NR>1 && $0!~/total:/
-考慮蔬菜行(不包括標題和總行 )
r=$2*$3
第二和第三字段的乘積結果
v=(v!="")? v"+"r : r
v=(v!="")? v"+"r : r
連接結果乘積值
veg_er
包含錯誤蔬菜信息( 蔬菜名稱,錯誤產品值和實際產品值)的數組
err_t+=$4
累積錯誤的總價值
t+=r
累計實際總價值
$0~/total/ && err_t
處理總行和錯誤事件
輸入項
akshay@db-3325:/tmp$ cat file
kg rate total
Tomato 4 50 100
potato 2 60 120
Beans 3 80 240
輸出量
akshay@db-3325:/tmp$ awk 'FNR>1{sum+= $2 * $3 }1;END{print "Total : "sum}' file
kg rate total
Tomato 4 50 100
potato 2 60 120
Beans 3 80 240
Total : 560
說明
awk ' # call awk
FNR>1{ # if no of lines of current file is greater than 1,
# then , this is to skip first row
sum+= $2 * $3 # sum total which is product of value
# in column2 and column3
}1; # 1 at the end does default operation,
# that is print current record ( print $0 )
# if you want to skip record being printed remove "1", so that script just prints total
END{ # end block
print "Total : "sum # print sum
}
' file
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.