使用Linux工具根据另一列的id对列的值求和

时间:2022-11-09 13:08:39

I have a file that is ' ' delimetered with a few fields. I know how to select a specific field and sum that by itself, but was wondering if there was a clean way of doing this using the linux utilities, otherwise I will do it in C.

我有一个文件“与几个字段分开”。我知道如何选择一个特定的字段并自己总结,但是想知道是否有一种干净的方式使用linux实用程序,否则我将在C中执行此操作。

An example of what I am talking about:

我正在谈论的一个例子:

FILE (there are more fields, but these are the only ones that matter for this case):

文件(有更多字段,但这些是唯一对这种情况重要的字段):

1 36
2 96
5 84422
2 2
1 655

1 36 2 96 5 84422 2 2 1 655

So, for this small example I would want:

所以,对于这个小例子我想要:

1 691
2 98
5 84422

1 691 2 98 5 84422

I am not sure if it is really worth trying to do using linux utilities, but since I am trying to expand my knowledge using those tools I figured I would ask if it was 1.) possible, 2.) practical.

我不确定是否真的值得尝试使用linux实用程序,但因为我试图使用这些工具扩展我的知识,我想我会问它是否可能,2。)实用。

2 个解决方案

#1


0  

$ perl -ne '/ /; $x{$`}+=$'\''; END { print "$_ $x{$_}\n" foreach keys %x; }' <<__END__
> 1 36
> 2 96
> 5 84422
> 2 2
> 1 655
> __END__
1 691
2 98
5 84422

#2


0  

awk '{ a[$1] += $2 } END { for (i in a) { print i " " a[i] } }' input.txt | sort -n

#1


0  

$ perl -ne '/ /; $x{$`}+=$'\''; END { print "$_ $x{$_}\n" foreach keys %x; }' <<__END__
> 1 36
> 2 96
> 5 84422
> 2 2
> 1 655
> __END__
1 691
2 98
5 84422

#2


0  

awk '{ a[$1] += $2 } END { for (i in a) { print i " " a[i] } }' input.txt | sort -n