[編輯,因爲發佈的問題是錯誤的] 我需要將此代碼的輸出保存在名爲'logfile'的文件中,並且在該日誌文件中只有計算錯誤。將錯誤消息重定向到日誌文件中bash
for f in *.log; do
awk 'NF && NR>1 && $0!~/total:/
{
things_cost=$2*$3;
overalltotal=(overalltotal!="")? overalltotal"+"things_cost : things_cost;
if(things_cost!=$4)
{
things_er[$1]=things_cost" instead of "$4
}
err_t+=$4; t+=things_cost;
}
$0~/total/ && err_t
{
print "Error in calculations:";
for(i in things_er)
{
print "Things total for "i" is wrong: it should be "things_er[i]
}
print "Overalltotal is wrong: It should be "t; next
}1' "$f" tmpfile && mv tmpfile logfile
done
使用上面的代碼,錯誤在日誌文件中以非常不可讀的格式重複。我正在使用下面給出的輸入文件。我需要在日誌文件
Date: 01-01-2007
Sold price total
thing1 3 7098 22394
thing2 2 6500 13000
thing3 20 300 6000
Overalltotal: 41394
-----------------------------------
Date: 04-01-2007
Sold price total
thing1 10 700 5000
thing2 48 900 43200
Overalltotal: 46020
你肯定有錯誤?只有awk命令返回代碼的命令大於0時,纔會填充error.log文件。 –
我試圖在計算輸入文件到日誌文件時輸出錯誤。當我試圖直接將這個'for'循環的輸出重定向到'日誌文件'時,它不起作用。 – User88
未設置的變量默認爲0;你可以在沒有條件的情況下直接寫'overalltotal + = things_cost'。 – chepner