Totals Per Region
Part of the Bash Scripting section of Coddy's Terminal journey. Lesson 33 of 39.
Challenge
MediumAdd the total sales of each region under the title. Keep everything you wrote so far: the checks and the title stay as they are.
- After the line that prints the title, add one
awkcommand that reads"$file"with-F,and skips the header line with the conditionNR > 1. - Keep one running sum per region in an awk array:
sum[$2] += $4adds the amount (column 4) to the entry for that region (column 2). - In the
ENDblock,for (r in sum) print r, sum[r]prints each region and its total, separated by one space. - awk visits the array in no fixed order, so pipe the result into
sortto 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 185The usage and the error for a missing file work as in the previous step.
Try it yourself
All lessons in Bash Scripting
1Arguments And Exit Codes
Script ArgumentsAll The ArgumentsExit CodesChecking ArgumentsRecap - Unit Converter4Strings And Arrays
Slicing StringsTrimming And ReplacingDefault ValuesArraysReading Files Line By LineRecap - CSV Report7Sales Report Project
Project OverviewCheck The Input FileTotals Per RegionSort And FormatA Top OptionSave The ReportPractice on your own: Terminal playground