2

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
4

Try:

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.

2

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
1

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.