在 bash 中输出到日志文件不正确

用户88

我有一个输入文件,如下所示:

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 的计算错误没有出现?另外,如何打印预期输出中显示的日期?

魏贝尔德

您的代码过于复杂和混乱。最好从头开始。

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章