0

I have a file like this:

user1, 10
user2, 5
user2, 6
user1, 15
user3, 23
user1, 15

I'd like to have totals by column 1 (user1, user2, user3), and make it look like this:

user1, 40
user2, 11
user3, 23

What would be the best way forward? A while loop on the first column and sum up the 2nd column as long as it's the same?

0

1 Answer 1

2

One-line awk:

$ awk -F, '{a[$1] += $2} END { for (x in a) printf "%s, %s\n", x, a[x] }' < data
user1, 40
user2, 11
user3, 23

That's rather straightforward, the field separator is set to the comma with -F, (this, and the comma in the output are about the only changes needed from the duplicate). $1 and $2 are the first and second fields, and since awk has associative arrays, collecting the sums is simple. You may need to sort the output afterward if that matters.


Sure, we could do this purely in Bash/ksh/zsh too, since it also supports associative arrays, but it would be uglier, slower and more prone to accidents with funny values. And only useful on a system that for some reason has a big shell, but no awk. (see edit history if you really want that...)

2
  • Both are valid bash code, but as you say, the second one is not the right way to process text in shells. Mar 7, 2018 at 9:48
  • Note that the order will not be deterministic. Mar 7, 2018 at 9:48

Not the answer you're looking for? Browse other questions tagged .