Course outline
Course / The terminal and the language

Read columns and add them up with awk

Lab

How to fetch and submit this lab

Once: install the tool and connect your account.

curl -fsSL https://gonomicon.com/install.sh | sh
gonomicon login

Each lab: download it, edit the file named in the instructions, then submit.

gonomicon fetch week-1/03-04-awk-fields-and-sums
cd 03-04-awk-fields-and-sums
gonomicon submit

Go installed? gonomicon test runs the visible test on your computer first. Submitting also runs hidden checks on our server.

Goal

The file testdata/sales.csv has one sale per line: date,item,amount. Print the item (field 2) of every line, then on the final line print the total of all the amounts (field 3).

Example

If testdata/sales.csv held:

2026-01-01,tea,4
2026-01-01,coffee,6
2026-01-02,tea,5

your script prints:

tea
coffee
tea
15

Rules

  • Edit answer.sh. Read testdata/sales.csv and print the result to the screen.
  • Fields are separated by commas. An item name can contain spaces (for example blue widget), and it must be printed whole.
  • Print one line per input line, in the original order, then the total as the very last line. Print only the number for the total, with no label.
  • A blank line in the file prints a blank line in the item list and adds nothing to the total. awk already behaves this way, so you do not need to filter anything.
  • All amounts are whole numbers.
  • Two awk commands, one after the other, is a perfectly good answer.
  • Do not edit testdata/sales.csv itself. Your script only prints.

What you'll practice

awk -F to set the separator, $2 and $3 for fields, and {sum += $3} END {print sum} to total a column.

Run it

gonomicon fetch week-1/03-04-awk-fields-and-sums
cd 03-04-awk-fields-and-sums
gonomicon test
gonomicon submit

Hints

  1. awk splits every line into fields. -F "," tells it the fields are separated by commas, and $2 is the second field.
  2. You need two jobs: print field 2 of every line, then add up field 3. Two awk commands, one after the other, work fine.
  3. First awk -F "," '{print $2}' FILE. Second awk -F "," '{sum += $3} END {print sum}' FILE. Put both in answer.sh, one per line.

Something wrong with this lesson? Report a problem