如何使用 bash 计算特定列的总和?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21342094/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How Can I calculate the sum of a specific column using bash?
提问by Nikleotide
I want to calculate the sum of a specific column using bash without using the print that specific column (I want to keep all the output columns of my pipeline and only sum one of them!)
我想使用 bash 计算特定列的总和而不使用打印该特定列(我想保留管道的所有输出列,并且只对其中一个列求和!)
回答by John1024
If you wanted to sum over, say, the second column, but print all columns in some pipeline:
如果你想总结第二列,但打印一些管道中的所有列:
cat data | awk '{sum+= ; print 1 2 3
4 5 6
7 8 9
} END{print "sum=",sum}'
If the file data looks like:
如果文件数据如下所示:
1 2 3
4 5 6
7 8 9
sum= 15
Then the output would be:
那么输出将是:
# file 'fields.txt':
1 foo
2 bar
10 baz
8 boz
# Step by step sum the first column:
awk '{s+=; print s, }' < fields.txt
# Output:
1 foo
3 bar
13 baz
21 boz
回答by grebneke
Do you want to continuously sum one column, step by step?
你想一步一步地连续总结一列吗?
Does is have to be bash
or can you use awk
:
是否必须bash
或您可以使用awk
:
$ cat data | echo $(( $( cut -d' ' -f2 | paste -s -d+ - ) ))
15
$
回答by Digital Trauma
Assuming the same input data as @John1024, you can use good ol' cut
and paste
and some basharithmetic:
假设相同的输入数据@ John1024,你可以用好醇”cut
以及paste
和一些bash的算术:
awk '{sum+=;} END { print "Total of 1st Column:" sum }1' abc.t6RrMm
The trick here is to tell paste
to insert +
as a delimiter, then perform bash arithmetic using $(( ))
on the resulting expression.
这里的技巧是告诉作为分隔符paste
插入+
,然后使用$(( ))
结果表达式执行 bash 算术。
Note I am just cat
ing the input data for illustrative purposes - it could be piped from another source, or the data file passed directly to cut
as well.
注意我只是cat
为了说明目的输入数据 - 它可以从另一个来源通过管道传输,或者也可以直接传递数据文件cut
。
回答by krishna murti
12 12 12
1 1 1
2 2 1
0 1 2
Given a file like:
给定一个文件,如:
##代码##Total of 1st Column is 15
.
第 1 列的总数是15
。