0

I have this sample data. I need to find the total for each color.

Input:

Blue,20
Blue,10
Black,13
Red,8
Black,10
Red,10
Blue,21

Output:

Blue,51
Black,23
Red,18

Thanks for your answer.

manpatha
  • 489
  • 4
  • 11
  • trying something like this "awk '{print $NF}' | awk '{n += $1}; END{print pat n}'" but not getting by each category. – manpatha Sep 10 '18 at 03:17

1 Answers1

1

In pure bash:

#!/usr/bin/env bash

declare -A totals=( )
while IFS=, read -r category value; do
  (( totals[$category] += value ))
done

for category in "${!totals[@]}"; do
  sum=${totals[$category]}
  echo "$category,$sum"
done

You can see this running -- emitting your desired output for the input at hand -- at https://ideone.com/5Ispzj

Charles Duffy
  • 280,126
  • 43
  • 390
  • 441