我有一个输入记事本文件,如下所示:
示例输入文件:
蔬菜和价格
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="s1" id="select1">
<option value="Facebook and Twitter">Facebook and Twitter</option>
<option value="Google and Yandex">Google and Yandex</option>
</select>
<select name="s2" id="select2">
<option value="Okay">Okay</option>
<option value="No">No</option>
</select>
总计:( 100 + 120 ++ 240)= 460
我需要将第2列和第3列相乘,并检查总数是否正确以及整体总数。如果那不对,我们需要在同一个文件中打印错误信息,如下所示
在这里输入代码
示例输出文件:
蔬菜和价格
kg rate total
Tomato 4 50 100
potato 2 60 120
Beans 3 80 240
总计:(200 + 120 ++ 240)= 560
计算错误: 番茄的Vegtotal错了:它应该是200而不是100 总的来说是错误的:它应该是560而不是460
到目前为止代码:
kg rate vegtotal
Tomato 4 50 200
potato 2 60 120
Beans 3 80 240
计算总数但不比较值。如何比较它们并打印到同一个文件?
答案 0 :(得分:1)
复杂 awk 解决方案:
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
详细说明:
NF && NR>1 && $0!~/total:/
- 考虑 veg 行(执行标题和总计行)
r=$2*$3
- 第二和第三个字段的产品的结果
v=(v!="")? v"+"r : r
- 连接生成的产品值
veg_er
- 包含错误vegs信息的数组( veg 名称,错误的产品值和真实的产品值)
err_t+=$4
- 累积错误的总值
t+=r
- 累积真实总值
$0~/total/ && err_t
- 处理总行和错误事件
答案 1 :(得分:0)
<强>输入强>
akshay@db-3325:/tmp$ cat file
kg rate total
Tomato 4 50 100
potato 2 60 120
Beans 3 80 240
<强>输出强>
akshay@db-3325:/tmp$ awk 'FNR>1{sum+= $2 * $3 }1;END{print "Total : "sum}' file
kg rate total
Tomato 4 50 100
potato 2 60 120
Beans 3 80 240
Total : 560
<强>解释强>
awk ' # call awk
FNR>1{ # if no of lines of current file is greater than 1,
# then , this is to skip first row
sum+= $2 * $3 # sum total which is product of value
# in column2 and column3
}1; # 1 at the end does default operation,
# that is print current record ( print $0 )
# if you want to skip record being printed remove "1", so that script just prints total
END{ # end block
print "Total : "sum # print sum
}
' file