>_ IzzyLab

Hands-on task

This task is step 12 of the course “Bash: expansions, arrays and quoting”

Word frequencies via an associative array

medium~10 min

In /root/words.txt there are words (one per line, with repeats). Write /root/count.sh that uses an associative array to count how many times the word error occurs (exactly that word: Error and errors are different words), and outputs the number. Run it, and put the result in /root/errors.txt. The script is easiest to write in the Editor tab above the terminal.

What you'll practise:
  • associative arrays
  • declare -A
  • while read loop
  • bash arithmetic
  • frequency counting

Topic breakdown

An associative array is a dictionary: the indexes are arbitrary string keys rather than numbers, which fits the frequency-counting task perfectly (the key is the word, the value is the counter). In bash such an array must be declared explicitly via declare with the -A flag, otherwise the shell assumes the indexes are numeric and the logic breaks. The file is read line by line with a while loop and the read command, feeding the content through redirection at the loop's input, and the counter for a key is incremented in an arithmetic context $(( ... )), where a nonexistent cell is treated as zero. After the traversal the sought value is simply retrieved from the cell by the required key.

What's checked

  1. errors.txt has the correct count of error occurrences
  2. count.sh counts from the current words.txt
  3. count.sh declares an associative array

What it looks like