How do I get Region-wise totals of Sales and Cost from the data below?
Region Sales Cost
North 139 35
South 786 295
South 312 117
East 288 108
North 149 56
West 508 127
North 145 54
South 379 142
East 500 188
eg.
North 433 145 and so on
Simple!, just use two arrays.
awk 'NR>1{uniqueSales[$1]+=$2; uniqueCost[$1]+=$3; next}
END{for (i in uniqueSales) print i,uniqueSales[i],uniqueCost[i]}' file
The code works by skipping the first record NR>1, where NR is a special variable keeping track of the line numbers of each line Awk is processing. Then we create a hash-map with index being $1 and two different arrays uniqueSales[$1]+=$2; uniqueCost[$1]+=$3 that increment the values from $2 and $3 respectively.
Once all the lines are processed. The END clause prints the values from both the arrays to get the required output needed.
South 1477 554
East 788 296
North 433 145
West 508 127
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With