我有一个输入文件,如下所示:
Date: 01-01-2007
thing1 3 7098 22394
thing2 2 6500 13000
thing3 20 300 6000
Overalltotal: 41394
-----------------------------------
Date: 04-01-2007
thing1 10 700 5000
thing2-Card 48 900 43200
Overalltotal: 46020
当前输出:
Error in calculations:
Things total for thing1 is wrong: it should be 7000 instead of 5000
Overalltotal is wrong: It should be 50200
预期产出:
Error in calculations:01-01-2007
Things total for thing1 is wrong: it should be 21294 instead of 22394
Overalltotal is wrong: It should be 40294
Error in calculations:04-01-2007
Things total for thing1 is wrong: it should be 7000 instead of 5000
Overalltotal is wrong: It should be 50200
到目前为止代码:
#!/bin/bash
# To create new files based on each date and copy the contents till the dashed line.
awk -F' ' '{fn=$1".log";sub(/^.* /,"",fn);print>fn;close(fn)}' \
FS='\n' OFS='\n' RS='---+\n' ORS='' $1
for f in *.log; do
(awk 'NF && NR>1 && $0!~/total:/{
r=$2*$3; v=(v!="")? v"+"r : r;
if(r!=$4){ things_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:" | "cat 1>&2";
for(i in things_er) { print "Things total for "i" is wrong: it should be "things_er[i] | "cat 1>&2"; }
print "Overalltotal is wrong: It should be "t | "cat 1>&2"; next
}1' "$f") 2> error_log
done
在我的错误日志文件中,我没有在计算中看到第一个日期的错误,我还需要在错误日志文件中打印日期。任何人都可以让我知道为什么01-01-2007的计算错误不会到来?另外,如何按预期输出显示日期?
答案 0 :(得分:0)
您的代码过于复杂和混乱。最好从头开始。
for
循环中的以下AWK命令打印所需的输出:
for f in *.log; do
awk '
/Date/ {
date=$2;
}
NF > 2 {
r = $2*$3;
if(r != $4) {
check_if_first_error();
printf "\tThings total for %s is wrong: it should be %d instead of %d\n", $1, r, $4;
}
overall_total += r;
}
/total/ {
if (overall_total != $2) {
check_if_first_error();
printf "\tOveralltotal is wrong: it should be %d instead of %d\n", overall_total, $2;
}
}
function check_if_first_error() {
if (!has_previous_error) {
printf "Error in calculations: %s\n", date;
has_previous_error = 1;
}
}
' "$f"
done &>error_log
error_log
:
Error in calculations: 01-01-2007
Things total for thing1 is wrong: it should be 21294 instead of 22394
Overalltotal is wrong: it should be 40294 instead of 41394
Error in calculations: 04-01-2007
Things total for thing1 is wrong: it should be 7000 instead of 5000
Overalltotal is wrong: it should be 50200 instead of 46020