Bash Script to Count Consonants in a String
echo "$string" | grep -o -i '[bcdfghjklmnpqrstvwxyz]' | wc -l in Bash to count consonants in a string.Examples
How to Think About It
Algorithm
Code
read -p "Enter a string: " string count=$(echo "$string" | grep -o -i '[bcdfghjklmnpqrstvwxyz]' | wc -l) echo "Number of consonants: $count"
Dry Run
Let's trace the input 'hello' through the code
Input string
string = 'hello'
Extract consonants
echo 'hello' | grep -o -i '[bcdfghjklmnpqrstvwxyz]' outputs: h e l l
Count consonants
wc -l counts 4 lines, so count = 4
| Consonant found |
|---|
| h |
| l |
| l |
Why This Works
Step 1: Extract consonants
The grep -o -i '[bcdfghjklmnpqrstvwxyz]' command finds each consonant letter ignoring case and prints each on a new line.
Step 2: Count lines
The wc -l command counts how many lines (letters) were output, which equals the number of consonants.
Step 3: Print result
The script stores the count and prints it with a message.
Alternative Approaches
read -p "Enter a string: " str count=0 for (( i=0; i<${#str}; i++ )); do c=${str:i:1} case "$c" in [bcdfghjklmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ]) ((count++)) ;; esac done echo "Number of consonants: $count"
read -p "Enter a string: " str count=$(echo "$str" | tr -cd 'bcdfghjklmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ' | wc -c) echo "Number of consonants: $count"
Complexity: O(n) time, O(n) space
Time Complexity
The script processes each character once to check if it is a consonant, so time grows linearly with string length.
Space Complexity
Extra space is used to hold the extracted consonants temporarily, proportional to the number of consonants.
Which Approach is Fastest?
Using tr -cd is generally faster than looping in Bash because it uses optimized system utilities.
| Approach | Time | Space | Best For |
|---|---|---|---|
| grep -o -i with wc -l | O(n) | O(n) | Simple and readable scripts |
| loop with case statement | O(n) | O(1) | Learning and small strings |
| tr -cd with wc -c | O(n) | O(n) | Performance and efficiency |
grep -o -i with a consonant pattern to easily extract consonants from a string.