Hi! First of all I’m having a great time!
I think I might have found an unexpected bug in the online testing of this exercise. I’m having no problems on my local machine. Something is going wrong with having apostrophes in my array values.
Anyway, here’s the code:
#!/usr/bin/bash
Main() {
local Input="$1"
local -A WordCount
read -ra Words <<< "${Input//[^a-zA-Z0-9\']/ }"
for Word in "${Words[@]}"; do
Word=${Word//[^a-zA-Z0-9\']}
Word=${Word/#\'/}
Word=${Word/%\'/}
Word=${Word,,}
if [[ $Word != "" ]]; then
((++WordCount["$Word"]))
fi
done
for Key in "${!WordCount[@]}"; do
printf "%s: %d\n" "$Key" "${WordCount[$Key]}"
done
}
Main "$@"
word_count.bats
✓ count one word
✓ count one of each word
✓ multiple occurrences of a word
✓ handles cramped lists
✓ handles expanded lists
✓ ignore punctuation
✓ include numbers
✓ normalize case
✓ with apostrophes
✓ with quotations
✓ substrings from the beginning
✓ multiple spaces not detected as a word
✓ alternating word separators are not detected as a word
✓ quotation for word with apostrophe
✓ contains shell globbing character
15 tests, 0 failures
Edit: I have technically solved the online problem by replacing the apostrophes with an underscore and afterwards switching them back. Hacky, but it works.
Thanks for the added context Glenn, it’s appreciated! Haven’t really used the shopt builtin much either, seems it could have saved me several other past headaches. This was driving me up the wall hahaha.
The bash track focuses on bash and not other utils. I would be fine without most the GNU utils. I think bc is the only one that really gets used (for floating point math).
While I certainly feel like that should be the case, a large portion of the community answers often use more than just bash and bc. gawk, grep and tr are ones I see often.
hmm, ubuntu 24.04 docker image includes bash 5.2. Safer (from a user’s perspectice – in terms of external tools expectations) to upgrade to that instead of moving to Alpine. It ships with mawk, which I’d suggest is good enough – if a user is relying on gnu-specific awk features, then they’re not trying hard enough to solve it in bash.