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

3 Answers 3

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.

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.