Course outline
Course / The terminal and the language

Sort lines and count duplicates

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-01-sort-and-count-duplicates
cd 03-01-sort-and-count-duplicates
gonomicon submit

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

Goal

Print every distinct name in testdata/names.txt once, in ascending order, with its count in front.

Example

If testdata/names.txt held:

apple
banana
apple

your script prints:

2 apple
1 banana

Each line is the count, one space, then the value. Names that appear once still print.

Rules

  • Edit answer.sh. Read the file testdata/names.txt; do not hard-code the names.
  • Sort the names before counting, so identical names sit next to each other.
  • Print one line per distinct value, in ascending order, with no header or extra lines.
  • uniq -c pads the count with spaces. That is fine: spaces at the start of a line are ignored when your output is checked.

What you'll practice

sort, uniq -c, and piping one command into another.

Run it

gonomicon fetch week-1/03-01-sort-and-count-duplicates
cd 03-01-sort-and-count-duplicates
gonomicon test
gonomicon submit

Hints

  1. sort puts identical lines next to each other.
  2. uniq -c collapses repeated lines and stamps each with its count, but only if they touch.
  3. Pipe one into the other: sort testdata/names.txt | uniq -c.

Something wrong with this lesson? Report a problem