Considering below file:
0,2,,,10
0,2,,,15
0,1,,,984
0,2,,,9
1,14,,,5
Using awk
, I need to calculate the total value in $5
per each $2
.
The desired output would look like below:
2,34
1,984
14,5
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. It only takes a minute to sign up.
Sign up to join this communityTry:
awk -F, '{a[$2]+=$5};END{for(i in a)print i","a[i]}' <file
A note that array traversal in POSIX awk is unspecified order.
With gnu
datamash
:
datamash -t ',' -s -g 2 sum 5 <infile
the output will be sorted by 2nd column:
1,984
14,5
2,34
I'd be tempted to use perl:
#!/usr/bin/env perl
use strict;
use warnings;
my %things;
while (<>) {
my ( undef, $key, @rest ) = split(/,/);
$things{$key} += pop(@rest);
}
foreach my $key ( sort { $a <=> $b } keys %things ) {
print "$key = $things{$key}\n";
}
You could condense that down to a one liner if needs be.