Using Raku (formerly known as Perl_6)
~$ raku -ne 'BEGIN my %h;
given .split(/\s/, 2, :skip-empty) -> ($k,$v) { %h{$k} += $v };
END .say for %h.sort;' file
Above is an answer coded in Raku, a member of the Perl-family of programming languages. You could consider preparing your input data by adapting the Raku answer here (sorting on a single column without uniquifying).
Code is called at the commandline with the -ne
(linewise, non-autoprinting) flags. A hash %h
is declared in a BEGIN
block. In the body of the linewise loop, each line is split
on whitespace into 2
pieces. The :skip-empty
parameter is used so that blank column values will throw an error.
The two elements are assigned to temporary variables $k
& $v
, which are referred to inside the block. Within the block, each $k
key is looked-up in the %h
hash. The key is added to the hash if not found, and the $v
second-column value is +=
assigned and/or added to that key's value (i.e. values accumulate). Here the +=
operator solves a lot of problems as it is really shorthand for %h{$k} = (%h{$k} // 0) + $v
.
Finally after all lines are read, the result is output in an END
block.
Sample Input:
a 1
a 5
a 6
b 2
b 3
b 0
c 1
c 7
Sample Output (using say
):
a => 12
b => 5
c => 8
To get tab-separated columns in the output, use put
instead of say
:
Sample Output (using put
):
a 12
b 5
c 8
https://raku.org
sort -u
on that input instead of justsort
? – Ed Morton Aug 23 '23 at 16:13cat
have e.g.a 1
? – Kusalananda Aug 24 '23 at 07:12