首页 文章

如何显示列的总和? [重复]

提问于
浏览
0

这个问题在这里已有答案:

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

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

如何添加这些数字(使用命令行)?我显示了这个列表打字

awk '{ print $4 }' cars

3 回答

  • 0

    鉴于:

    $ 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
    
  • 1

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

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

    1st Solution in awk: 请问您可以尝试一次 . (由于您的尝试显示,我正在第4列的总和,编写了一个动态命令,您只需更改变量's value and it will take that column' s SUM)

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

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

    Explanation of above code:

    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.
    

    2nd Solution in bash: 考虑到Input_file中的行只有1个条目 .

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

相关问题