>_ IzzyLab

Hands-on task

This task is step 6 of the course “First steps with text”

Count the votes

easy~5 min

A team was choosing a language for its internal scripts. Each vote is written on its own line in /root/data/votes.txt.

Count how many votes each language got and save the result to /root/results.txt: one line per language, each with the vote count and the name, the way uniq -c prints it (for example, 3 java). The order of lines doesn't matter. Do it in one line by joining commands with the | sign.

What you'll practise:
  • uniq -c
  • sort
  • pipe |
  • counting repeats

Topic breakdown

uniq removes repeated lines, and with the -c flag (count) it also writes in front of each line how many times it was repeated. An important detail: uniq compares a line only with the neighboring one. If identical lines are scattered around the file, it counts each clump separately.

That's why uniq almost always comes after sort, which gathers identical lines together. Commands are joined by a pipe |: the output of the left command goes to the input of the right one, with no files in between.

printf 'b\na\nb\n' | uniq -c          # 1 b, 1 a, 1 b — the repeats aren't adjacent
printf 'b\na\nb\n' | sort | uniq -c   # 1 a, 2 b

What's checked

  1. results.txt has lines like "number name"
  2. Each language appears in the result exactly once
  3. Each language has the right number of votes

What it looks like