shell scripting-bash中的算术计算 [英] Arithmetic calculation in shell scripting-bash

查看:75
本文介绍了shell scripting-bash中的算术计算的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个输入的记事本文件,如下所示:

I have an input notepad file as shown below:

样本输入文件:

蔬菜和价格

kg  rate    total 
Tomato  4   50  100
potato  2   60  120 
Beans   3   80  240

总分:(100 + 120 ++ 240)= 460

我需要将第2列和第3列相乘,并检查总数是否正确以及总数.如果不正确,我们需要在同一文件中打印一条错误消息,如下所示

I need to multiply the column 2 and column 3 and check the total if it is right and the overall total as well. If that's not right we need to print in the same file as an error message as shown below

在此处输入代码

示例输出文件:

蔬菜和价格

kg  rate    vegtotal

Tomato  4   50  200
potato  2   60  120 
Beans   3   80  240

总分:(200 + 120 ++ 240)= 560

计算错误: 西红柿的素食总量是错误的:应该是200,而不是100 总体错误:应为560,而不是460

Error in calculations: Vegtotal for tomato is wrong: It should be 200 instead of 100 Overalltotal is wrong: It should be 560 instead of 460

到目前为止的代码:

for f in Date*.log; do
       awk 'NR>1{ a[$1]=$2*$3 }{ print }END{ printf("\n");
            for(i in a)
       { if(a[i]!=$4)
              { print i,"Error in calculations",a[i] }
            } }' "$f" > tmpfile && mv tmpfile "$f"; 

done

它计算总计,但不比较值.如何比较它们并打印到同一文件?

It calculates the total but not comparing the values. How can I compare them and print to same file?

推荐答案

复杂的 awk 解决方案:

Complex awk solution:

awk 'NF && NR>1 && $0!~/total:/{ 
         r=$2*$3; v=(v!="")? v"+"r : r; 
         if(r!=$4){ veg_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:"; 
         for(i in veg_er) { print "Veg total for "i" is wrong: it should be "veg_er[i] } 
         print "Overalltotal is wrong: It should be "t" instead of "err_t; next 
     }1' inputfile

输出:

kg  rate    total 
Tomato 4 50 200
potato 2 60 120
Beans 3 80 240

Overalltotal: (200+120+240) = 560
Error in calculations:
Veg total for Tomato is wrong: it should be 200 instead of 100
Overalltotal is wrong: It should be 560 instead of 460


详细信息:


Details:

  • NF && NR>1 && $0!~/total:/-考虑 veg 行(排除 header total 行)

  • NF && NR>1 && $0!~/total:/ - considering veg lines (excuding header and total lines)

r=$2*$3-第二和第三字段的 product 的结果

r=$2*$3 - the result of product of the 2nd and 3rd fields

v=(v!="")? v"+"r : r-级联所得的产品

veg_er-包含错误蔬菜信息( veg 名称,错误乘积值和 real 乘积值)的数组

veg_er - the array containing erroneous vegs info (veg name, erroneous product value, and real product value)

err_t+=$4-累积错误的总值

t+=r-累计 real 总价值

$0~/total/ && err_t-处理总计行和错误事件

这篇关于shell scripting-bash中的算术计算的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆