【问题标题】:Calculating the sum and average计算总和和平均值
【发布时间】:2013-06-20 08:41:26
【问题描述】:

我的输入文件是商品价格表,在特定商品中,我想使用awk计算大米商品的总和和平均值?

Chenna Black |1|76.00|Chenna
Chenna White big|1|102.00|Chenna
Chenna White small|1|82.00|Chenna
Dhal-Gram|1|78.00|Dhal
Dhal-Moong|1|76.00|Dhal
Dhal-Orid|1|72.00|Dhal
Dhal-Toor|1|68.00|Dhal
Dhal-Green gram|1|88.00|Dhal
Rajma-Black|1|72.00|Rajma
Rajma-Pink|1|80.00|Rajma
Rice-Basmanthi|1|80.00|Rice
Rice-Boiled|1|42.00|Rice
Rice-Idly|1|33.00|Rice
Rice-IGBasamanthi|1|99.00|Rice
Rice-Karanatka Ponni|1|38.00|Rice
Rice-Nirapara Silky|1|235.00|Rice
Rice-Raw|1|40.00|Rice
Rice-Roasted Gram|1|100.00|Rice

【问题讨论】:

  • 是的,我试过这样 BEGIN { FS = "|" } $4 ~ /Rice/ { n = n + 1;项目 = 项目 + 3 美元; } END{ if ( n > 0 ) { # print n,"items,","total items pay is:", items," items average:", items/n # 单行打印 print n,"items, " print "支付的总项目数是:" items print "平均项目数:" items/n } else { print "item is not found " } }
  • 开始 { FS = "|" } $4 ~ /Rice/ { n = n + 1;项目 = 项目 + 3 美元; } END{ if ( n > 0 ) { # print n,"items,","total items pay is:", items," items average:", items/n # 单行打印 print n,"items, " print "支付的总项目数是:" items print "平均项目数:" items/n } else { print "item is not found" } } 8 个项目,支付项目总数:667,平均项目数:83.375

标签: awk gawk


【解决方案1】:

使用awk的所有大米项目的总和和平均值:

$ awk -F'|' '$4=="Rice"{s+=$3;c++}END{printf "sum: %.2f avg: %.2f\n",s,s/c}' file
sum: 667.00 avg: 83.38

【讨论】:

  • 相同的输入文件。但我的问题是如果你想通过命令行检查项目是否存在。假设如果你拿米饭项目它会显示消息项目存在。如果你检查任何其他item 它将显示消息 item is not found.
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-10-09
  • 1970-01-01
  • 2018-09-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-05-08
相关资源
最近更新 更多