0
0
Bash-scriptingHow-ToBeginner · 2 min read

Bash Script to Count Consonants in a String

Use echo "$string" | grep -o -i '[bcdfghjklmnpqrstvwxyz]' | wc -l in Bash to count consonants in a string.
📋

Examples

Inputhello
Output3
InputBash Scripting
Output9
Inputaeiou
Output0
🧠

How to Think About It

To count consonants, look at each letter in the string and check if it is a consonant letter (not a vowel). Count all such letters ignoring case.
📐

Algorithm

1
Get the input string.
2
Convert the string to lowercase or uppercase to ignore case.
3
Extract all consonant letters from the string.
4
Count how many consonant letters were found.
5
Print the count.
💻

Code

bash
read -p "Enter a string: " string
count=$(echo "$string" | grep -o -i '[bcdfghjklmnpqrstvwxyz]' | wc -l)
echo "Number of consonants: $count"
Output
Enter a string: hello Number of consonants: 3
🔍

Dry Run

Let's trace the input 'hello' through the code

1

Input string

string = 'hello'

2

Extract consonants

echo 'hello' | grep -o -i '[bcdfghjklmnpqrstvwxyz]' outputs: h e l l

3

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

Using a loop and case statement
bash
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"
This method uses a loop and is easy to understand but slower for very long strings.
Using tr and grep
bash
read -p "Enter a string: " str
count=$(echo "$str" | tr -cd 'bcdfghjklmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ' | wc -c)
echo "Number of consonants: $count"
This method uses <code>tr -cd</code> to delete all but consonants and counts characters, which is efficient.

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.

ApproachTimeSpaceBest For
grep -o -i with wc -lO(n)O(n)Simple and readable scripts
loop with case statementO(n)O(1)Learning and small strings
tr -cd with wc -cO(n)O(n)Performance and efficiency
💡
Use grep -o -i with a consonant pattern to easily extract consonants from a string.
⚠️
Forgetting to use case-insensitive matching causes missing uppercase consonants.