Course / The terminal and the language
Read columns and add them up with awk
How to fetch and submit this lab
Once: install the tool and connect your account.
curl -fsSL https://gonomicon.com/install.sh | sh
gonomicon loginEach 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 submitGoal
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. Readtestdata/sales.csvand 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.
awkalready behaves this way, so you do not need to filter anything. - All amounts are whole numbers.
- Two
awkcommands, one after the other, is a perfectly good answer. - Do not edit
testdata/sales.csvitself. 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
awksplits every line into fields.-F ","tells it the fields are separated by commas, and$2is the second field.- You need two jobs: print field 2 of every line, then add up field 3. Two
awkcommands, one after the other, work fine. - First
awk -F "," '{print $2}' FILE. Secondawk -F "," '{sum += $3} END {print sum}' FILE. Put both in answer.sh, one per line.