【问题标题】:Using awk for calculations, getting extra lines in the output使用 awk 进行计算,在输出中获得额外的行
【发布时间】:2020-07-04 01:07:07
【问题描述】:

我正在尝试使用 awk 命令和一些计算打印一个简单的报告。 这是输入文件:

1   Syed-Yamin   3   500
2   Ilia-Nika    4   400
3   Mike-Ro      5   300
4   Witold-Ryb   2   200
5   Farhan-F     1   500

在报表中我要打印第一列、第二列以及每行第三列和第四列相乘的计算结果。另外,我想在底部打印每行所有乘法的总和。我在输出中得到了一些额外的行,并想清理它们。所以最终结果应该是这样的:

1   Syed-Yamin   1500
2   Ilia-Nika    1600
3   Mike-Ro      1500
4   Witold-Ryb   400
5   Farhan-F     500
Total amount = $5500
awk 'BEGIN {total=0;}
{print "$1, $2, ($3 * $4)";}
total=total+($3 * $4)
END {print "Total Amount = $", total;}' input

awk print with lots of extra lines

【问题讨论】:

  • 你的代码在哪里?
  • 我拍了一张快照并发布了,但后来编辑了主题以添加代码。

标签: linux awk


【解决方案1】:

这里我为你修好了……

$ awk -v OFS='\t' '{$3 *= $4; NF--; total += $3}1
               END {print "","Total Amount =", "$"total}' file | 
 column -ts$'\t'

1  Syed-Yamin      1500
2  Ilia-Nika       1600
3  Mike-Ro         1500
4  Witold-Ryb      400
5  Farhan-F        500
   Total Amount =  $5500

这种格式可能更好

$ awk '{printf "%d\t%s\t%5d\n",$1,$2,$3*=$4; total+=$3}
   END {print "\tTotal Amount =\t$"total}' file | 
   column -ts$'\t'

1  Syed-Yamin       1500
2  Ilia-Nika        1600
3  Mike-Ro          1500
4  Witold-Ryb        400
5  Farhan-F          500
   Total Amount =  $5500

【讨论】:

  • 非常感谢!出于某种原因,我真的更喜欢你的第一个解决方案。
猜你喜欢
  • 2015-07-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多