Bash:来自标准输出的整数值的总和

标签 bash integer sum cut

有办法吗?

我有一组数据,其中包含一个整数字段:

cat myinput
14 bytes long.
36 bytes long.
32 bytes long.

我想在这些文本行中添加整数值以给出总和。所以在上面的例子中,整数值的总和是 82。我曾想过使用类似的东西:

cat myinput | cut -f1 -d' ' | <...add code here to add the filtered integers...> 

看来我必须以某种方式进行 expr,但我不知道该怎么做。

有人能帮忙吗?

最佳答案

让我们用 awk 来做吧?

$ awk 'a+=$1; END{print a}' file
14 bytes long.
36 bytes long.
32 bytes long.
82

使用 bash:

f=0
while read i
do
  n=$(echo $i | cut -d' ' -f1)
  tot=$(($n + $tot))
done < file

$ echo $tot
82

关于Bash:来自标准输出的整数值的总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16892945/

相关文章:

linux - 无法使用 stdout exec 结束 Bash 脚本

c - 在 C 中打印后台进程列表的函数(如作业)?

c - ObjC 中的 long long int

JavaScript - 近似数字

postgresql - Postgresql如何获取一个月内不同产品总金额的最大金额?

json - 在 jq 中作为变量赋值

bash - Bash 中两个列表的交集

python - 输出从 0 到 255 的整数的哈希函数?

python - 二维数组的python总和如何返回列表

带 SUM 和 order 的 MySQL 查询