How to display the sum of a column?
本问题已经有最佳答案,请猛点这里访问。
如何从名为
1 2 3 4 5 6 7 8 9 10 11 12 | 73 60 45 102 15 50 115 30 10 180 85 25 |
如何(使用命令行)添加这些数字?我把这张单子拿出来打字了
1 | awk '{ print $4 }' cars |
鉴于:
1 2 3 4 5 6 7 8 9 10 11 12 13 | $ cat file 73 60 45 102 15 50 115 30 10 180 85 25 |
你可以做到:
1 2 | $ paste -sd+ file | bc 790 |
或者,给定多列文件:
1 2 3 4 5 6 7 8 9 10 11 12 13 | $ 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 |
您可以使用
1 2 | $ cut -f 2 file | paste -sd+ - | bc 790 |
这是一种在命令行上执行的方法,但不是awk。
1 2 3 4 | vim /tmp/text let sum=0 for X in `cat /tmp/text`; do let sum=$sum+$X; done echo $sum |
awk中的第一个解决方案是:请您尝试以下操作一次。(因为您的尝试显示了第4列的总和,所以我取了它,编写了一个动态命令,您只需要更改变量的值,然后它将取该列的总和)
1 | awk -v column_number=4 '{sum+=$column_number} END{print"SUM of column" column_number" is:" sum}' Input_file |
通过运行上面的代码,您可以给出变量
以上代码说明:
1 2 3 4 5 6 7 | 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中的第二个解决方案:考虑到输入文件中的行只有一个条目。
1 | while read line; do sum=$(($sum+$line)) ; done <"Input_file"; echo"$sum" |