【问题标题】:How to display the sum of a column? [duplicate]如何显示一列的总和? [复制]
【发布时间】:2019-05-10 07:27:54
【问题描述】:

如何从名为 cars 的文件中找到该列的总和?

73
60
45
102
15
50
115
30
10
180
85
25

如何将这些数字相加(使用命令行)? 我显示了这个列表输入

awk '{ print $4 }' cars

【问题讨论】:

  • sum += $4;print sum 尝试后可以再次拍摄。
  • 更准确地说是awk '{sum += $4} END{print sum}',而且你想要的垂直排列的项目或图形的单词是column -- coulomb 是一个电荷单位等于 1 安培持续 1 秒。
  • 大量投票发生 :( 对于所有帖子
  • 是的,这将取决于@jww 他的古怪把戏。我会投票支持所有答案以进行补偿。

标签: bash awk


【解决方案1】:

给定:

$ cat file
73
60
45
102
15
50
115
30
10
180
85
25

你可以这样做:

$ paste -sd+ file | bc
790

或者,给定一个多列文件:

$ cat file
0   73  1
2   60  3
4   45  5
6   102 7
8   15  8
9   50  10
11  115 12
13  30  14
15  10  16
17  180 18
19  85  20
21  25  22

您可以使用cut获取感兴趣的列:

$ cut -f 2 file | paste -sd+ - | bc
790

【讨论】:

    【解决方案2】:

    这是一种在命令行上执行此操作的方法,但不是 awk。

    vim /tmp/text
    let sum=0
    for X in `cat /tmp/text`; do let sum=$sum+$X; done
    echo $sum
    

    【讨论】:

    • 虽然我没有在这里投反对票。恕我直言,您无需在 for 循环的每次迭代中读取 Input_file 您可以看到这个链接,我们可以在 bash 中使用循环来获得一次总和 stackoverflow.com/a/53688677/5866580
    【解决方案3】:

    awk 中的第一个解决方案:您能否尝试关注一次。(我正在计算第 4 列的总和,因为您的尝试表明它已经编写了一个动态命令,您只需要更改变量的值,然后它将采用该列的 SUM)

    awk -v column_number=4 '{sum+=$column_number} END{print "SUM of column " column_number " is: " sum}'  Input_file
    

    通过运行上面的代码,您可以在变量column_number 中给出任何列号,并且可以获取其中的一些。如果您有任何其他要求,请在您的帖子中的代码标签中向我们展示示例输入和预期的示例输出。

    以上代码说明:

    awk -v column_number=4 '    ##Starting awk program here and setting variable column_number value to 4 you could change it as per your column number too, for which you want to take SUM for all lines of Input_file.
    {                           ##Starting a BLOCK here.
      sum+=$column_number       ##Creating a variable named SUM whose value is value of current lines $column_number value and it keep adding SUMs value to its own to get cumulative sum of all columns in all lines.
    }                           ##Closing BLOCK here.
    END{                        ##Mentioning awk program END block here, it will be executed when an Input_file is being done with reading.
      print "SUM of column " column_number " of all lines in Input_file is: " sum     ##Printing SUM variable value here.
    }'  Input_file              ##Mentioning Input_file name here.
    

    bash 中的第二个解决方案:考虑到您在 Input_file 中的行只有 1 个条目。

    while read line; do    sum=$(($sum+$line)) ; done < "Input_file"; echo "$sum"
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-11-17
      • 1970-01-01
      • 1970-01-01
      • 2021-01-08
      • 2016-11-19
      • 1970-01-01
      • 1970-01-01
      • 2011-04-16
      相关资源
      最近更新 更多