Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort keys and Sum their values in bash

Tags:

bash

awk

I have a list of strings (stdin) like next:

1 pineapples
28 apples
16 oranges
8 apples
2 apples
2 oranges
56 pineapples

Is there a native way (like sort & uniq -c) with which I can merge and sum them like this:

38 apples
18 oranges
57 pineapples

like sort |uniq -c do, but not only for occurrences number?

like image 827
cardinal-gray Avatar asked Dec 18 '17 20:12

cardinal-gray


1 Answers

Try this one:

awk '{a[$2] += $1} END{for (i in a) print a[i], i}' < in.txt

The output

38 apples
57 pineapples
18 oranges
like image 129
Pavel Avatar answered Oct 17 '22 02:10

Pavel