如何使用 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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 09:21:36  来源:igfitidea点击:

How Can I calculate the sum of a specific column using bash?

bashsum

提问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 bashor 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' cutand pasteand some basharithmetic:

假设相同的输入数据@ John1024,你可以用好醇”cut以及paste和一些bash的算术:

awk '{sum+=;} END { print "Total of 1st Column:" sum }1' abc.t6RrMm 

The trick here is to tell pasteto insert +as a delimiter, then perform bash arithmetic using $(( ))on the resulting expression.

这里的技巧是告诉作为分隔符paste插入+,然后使用$(( ))结果表达式执行 bash 算术。

Note I am just cating the input data for illustrative purposes - it could be piped from another source, or the data file passed directly to cutas 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