Bash Exercises
Time to practise! Each exercise has a starter playground that runs as-is and prints a placeholder result, so you can see the expected format. Replace the TODO parts, press ▶ Run, and compare your output with the "Expected" lines. If you get stuck, open the solution, but give it a few minutes first: struggling a little is how the commands stick.
| # | Exercise | Topics |
|---|---|---|
| 1 | Word statistics | wc, tr, pipes |
| 2 | Biggest files | find, sort, head |
| 3 | Sales by region | awk, associative arrays |
| 4 | Batch rename | for, globs, parameter expansion |
| 5 | Failed logins | grep, cut, sort, uniq |
| 6 | Input validator | functions, [[ =~ ]], case |
| 7 | Options with getopts | script arguments |
| 8 | Config file loader | while read, arrays, IFS |
1. Word statistics
Count the lines, words and distinct words (case-insensitive) in poem.txt, and print the most frequent word.
Expected:
text
lines: 4
words: 23
distinct: 13
most frequent: thebash · try it yourself
cat > poem.txt <<'TXT'
The wind and the rain
and the sound of the sea
sing the song of the night
to the town and the tree
TXT
# TODO: compute the four values with wc, tr, sort and uniq
echo "lines: 0"
echo "words: 0"
echo "distinct: 0"
echo "most frequent: ?"lines: 0
words: 0
distinct: 0
most frequent: ?
Show solution
bash
echo "lines: $(wc -l < poem.txt)"
echo "words: $(wc -w < poem.txt)"
words() { tr -cs '[:alpha:]' '\n' < poem.txt | tr '[:upper:]' '[:lower:]' | grep -v '^