Menu
CoddyTech

Totals Per Region

Part of the Bash Scripting section of Coddy's Terminal journey. Lesson 33 of 39.

challenge icon

Challenge

Medium

Add the total sales of each region under the title. Keep everything you wrote so far: the checks and the title stay as they are.

  1. After the line that prints the title, add one awk command that reads "$file" with -F, and skips the header line with the condition NR > 1.
  2. Keep one running sum per region in an awk array: sum[$2] += $4 adds the amount (column 4) to the entry for that region (column 2).
  3. In the END block, for (r in sum) print r, sum[r] prints each region and its total, separated by one space.
  4. awk visits the array in no fixed order, so pipe the result into sort to list the regions in alphabetical order.

Try it: run bash report.sh sales.csv. It prints:

=== Sales Report ===
East 405
North 425
South 335
West 185

The usage and the error for a missing file work as in the previous step.

Try it yourself

Terminal

All lessons in Bash Scripting

Practice on your own: Terminal playground