[编辑,因为发布的问题是错误的] 我需要将此代码的输出保存在名为' logfile'的文件中。并且只有该日志文件中的计算错误。
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
答案 0 :(得分:-1)
你的awk代码没有向stderr输出任何内容,我想你想在stderr和stdout上都有输出。为此,您必须执行以下操作
(echo "test" | awk '{print $0; print $0." error" | "cat 1>&2" }') > log 2> err_log
这里的重要部分是| "cat 1>&2"
,您必须在每次打印错误后附加log
。在awk命令结束时,您必须使用err_log
和>
将stdout重定向到2>
文件并将stderr重定向到echo "\
#################################
Date: 01-01-2007
thing1 3 7098 22394
thing2 2 6500 13000
thing3 20 300 6000
--------------------------------
Date: 04-01-2007
thing4 10 700 5000
thing5 48 900 43200
Overalltotal: 46020
#################################
total 89593" > test.csv
(awk '
!/^#/ && !/^total/ && $2~/[0-9]+/ && $3~/[0-9]+/ && $4~/[0-9]+/ {
line_cost = $2*$3
real_total += line_cost;
precomputed_total += $4;
if(line_cost!=$4)
errors[NR]="Error (product "$1": line " NR ") line cost is " line_cost" != " $4;
print "\t"$0;
}
/^total/ && length(errors)>0 {
print "\tErrors in item totals:" | "cat 1>&2";
for(i in errors)
print "\t\t"errors[i] | "cat 1>&2";
if (real_total != precomputed_total)
print "\tPre-computed total: "$2 | "cat 1>&2";
print "\tOverall total based on items totals: "precomputed_total | "cat 1>&2";
print "\tOverall total based on items price*quantity: "real_total | "cat 1>&2";
}' test.csv) > log 2> err_log
echo "Content of log file"
cat log
echo "Content of err_log file"
cat err_log
文件。
以下是它的工作原理:
Log:
thing1 3 7098 22394
thing2 2 6500 13000
thing3 20 300 6000
thing4 10 700 5000
thing5 48 900 43200
Error log:
Errors in item totals:
Error (product thing1: line 3) line cost is 21294 != 22394
Error (product thing4: line 8) line cost is 7000 != 5000
Pre-computed total: 89593
Overall total based on items totals: 89594
Overall total based on items price*quantity: 90494
输出以下内容:
{{1}}