Here is one way with sorting, GNU sed and bc:
sort infile | sed -r ':a; N; s/([^ ]+) +([^\n]+)\n\1/\1 \2 +/; ta; P; D' | sed -r 'h; s/[^ ]+/echo/; s/$/ | bc/e; G; s/([^\n]+)\n([^ ]+).*/\2 \1/'
Output:
bar 20 foo 40
The first sed joins adjacent lines with the same key adding + between numbers, the second passes the sums to bc.
source share