summing the values of a column based on the id of another column using Linux tools
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.
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
So, for this small example I would want:
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.
$ 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
awk '{ a[$1] += $2 } END { for (i in a) { print i " " a[i] } }' input.txt | sort -n
精彩评论