Sort And Format
Part of the Bash Scripting section of Coddy's Terminal journey. Lesson 34 of 39.
Challenge
MediumPut the biggest region first, line the numbers up in a column and add a grand total. Keep the checks and the title; this step changes the region lines.
- In the
ENDblock, print the total first and the region second:print sum[r], r. - Replace
sortwithsort -nr:-ncompares the lines as numbers and-rputs the largest first. - Pipe the sorted lines into
while read -r amount regionand print each one withprintf '%-10s%6d\n' "$region" "$amount".%-10spads the region to 10 characters on the right, and%6dright-aligns the number in 6 characters. - After the loop, use a second
awkto add up column 4 of every sale except the header, and print it with the same format and the labelTotal.
Try it: run bash report.sh sales.csv. It prints:
=== Sales Report ===
North 425
East 405
South 335
West 185
Total 1350Every number ends in the same column, the sixteenth character of the line. The usage and the error for a missing file stay as they were.
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