>_ IzzyLab

Hands-on task

This task is step 10 of the course “awk and datamash: reports from tables”

awk: sum by group

medium~5 min

/root/spend.txt has two columns: a category and an amount. Sum the amounts for each category and write lines of the form category amount to /root/by_cat.txt. The order of the lines doesn't matter.

What you'll practise:
  • awk
  • associative array
  • grouping by key
  • for-in loop
  • END block

Topic breakdown

When you need to sum not a grand total but each key value separately, in awk you use an associative array — its index is not a number but an arbitrary string, for example the category from the first field. In a single pass over the file, you add the value from the amount column to the cell of the given key, gradually building a "key → sum" table. It must be printed in the END block, once the whole file has been read: you iterate the array over its keys and, for each key, output the accumulated sum, while the iteration order doesn't matter per the task.

What's checked

  1. sums for every category are correct

What it looks like