Menu
CoddyTech

Sort And Format

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

challenge icon

Challenge

Medium

Put 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.

  1. In the END block, print the total first and the region second: print sum[r], r.
  2. Replace sort with sort -nr: -n compares the lines as numbers and -r puts the largest first.
  3. Pipe the sorted lines into while read -r amount region and print each one with printf '%-10s%6d\n' "$region" "$amount". %-10s pads the region to 10 characters on the right, and %6d right-aligns the number in 6 characters.
  4. After the loop, use a second awk to add up column 4 of every sale except the header, and print it with the same format and the label Total.

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

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

Every 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

Terminal

All lessons in Bash Scripting

Practice on your own: Terminal playground