>_ IzzyLab

Hands-on task

This task is step 16 of the course “Text in the terminal: grep, sed, awk”

Expenses by department from a CSV

medium~5 min

/root/expenses.csv has lines department,amount — each purchase separately, departments repeat in random order. Compute the total for each department and write lines department total (separated by a space) to /root/by_dept.txt. Line order doesn't matter.

What you'll practise:
  • awk
  • -F delimiter
  • associative array
  • grouping
  • END block

Topic breakdown

Grouping with a sum — what SQL writes as GROUP BY with SUM — is done in awk with an associative array: the key is the value of the grouping column, the cell holds the running total. The whole file is read once, and printing the totals moves to END, when all lines have been accounted for. For CSV the field separator has to change: by default awk splits on spaces, and the whole line sales,1200 would be one field.

What's checked

  1. totals per department are correct

What it looks like