2017-06-22 62 views
0

我有两个文本文件,如下所示。其中包含每个项目的数量,价格,总计和所有项目在每个文件结束时的总计。bash:从输入文件读取并执行计算并将错误写入日志文件

file1.txt

Date: 05-10-2016 
Item1 5 1000 6000 
Item2 7 1500 10500 
Item3 4 2000 8000 
Total: 24500 

file2.txt

Date: 07-12-2016 
Item1 7 750 5250 
Item2 3 900 2700 
Item3 8 1000 9000 
Total: 16950 

我试图通过每个文件和总再次通过添加出现在文件中个别项目的价格阅读。当总数不匹配时,它应该在error.txt文件中写入一条错误消息,清楚地说明哪些天有数据存在问题。

error.txt

Date: 05-10-2016 
Item1 5 1000 6000 : Item total calculation is wrong. 
Total: 24500 : All items total calculation is wrong. 

Date: 07-12-2016 
Item3 8 1000 9000 : Item total calculation is wrong. 
Total: 16950 : All items total calculation is wrong. 
+0

你尝试过这么远吗? f in * .txt中的 –

+0

;做 awk'NR> 1 {a [$ 1] = $ 2 * $ 3} {print} END {printf(“\ n”); (打印i,“计算中的错误”,a [i]} }'“$ f”> tmpfile && mv tmpfile“$ f”; for(i in f) done – Avinash

+0

请注意[注释是临时的,可以随时删除](https://stackoverflow.com/help/privileges/comment)。如果您需要提供其他信息,例如您尝试过的代码,请点击帖子下方的“[edit]”**链接更新您的问题。有关详细信息,请参见(https://meta.stackexchange.com/q/19756/204869)。谢谢。 – Pang

回答

0
awk '/Date/{d=$0;t=0;p=0;next;} 
    /Total/{if(t!=int($2)){if(p==0){print d; p=1;}; print $0,":","All items total calculation is wrong."};next;} 
    {k=int($2)*int($3);t+=k;if(k!=int($4)){if(p==0){print d; p=1;}; print $0,":","Item total calculation is wrong."}}' file1 file2 >error.txt 

输出:

cat error.txt 

Date: 05-10-2016 
Item1 5 1000 6000 : Item total calculation is wrong. 
Total: 24500 : All items total calculation is wrong. 
Date: 07-12-2016 
Item3 8 1000 9000 : Item total calculation is wrong. 
Total: 16950 : All items total calculation is wrong. 
相关问题