Bash Script to Count Vowels in a String
Use
echo "$string" | grep -o -i '[aeiou]' | wc -l in Bash to count vowels in a string, where $string is your input text.Examples
Inputhello
Output2
InputBash Scripting
Output4
Inputxyz
Output0
How to Think About It
To count vowels, look at each character in the string and check if it is a vowel (a, e, i, o, u). Count how many times vowels appear regardless of case.
Algorithm
1
Get the input string.2
Convert the string to lowercase or ignore case.3
Extract all vowels from the string.4
Count the number of vowels extracted.5
Return the count.Code
bash
#!/bin/bash read -p "Enter a string: " string count=$(echo "$string" | grep -o -i '[aeiou]' | wc -l) echo "Number of vowels: $count"
Output
Enter a string: hello
Number of vowels: 2
Dry Run
Let's trace the input 'hello' through the code
1
Input string
string = 'hello'
2
Extract vowels
echo 'hello' | grep -o -i '[aeiou]' outputs: e\no
3
Count vowels
wc -l counts 2 lines (vowels)
| Vowel Found |
|---|
| e |
| o |
Why This Works
Step 1: Extract vowels
The grep -o -i '[aeiou]' command finds each vowel in the string, ignoring case, and prints each on a new line.
Step 2: Count lines
The wc -l command counts how many lines (vowels) were printed, giving the total vowel count.
Alternative Approaches
Using a loop and case statement
bash
#!/bin/bash read -p "Enter a string: " string count=0 for (( i=0; i<${#string}; i++ )); do char=${string:i:1} case $char in [aeiouAEIOU]) ((count++)) ;; esac done echo "Number of vowels: $count"
This method is more manual but does not rely on external commands like grep or wc.
Using tr and grep
bash
#!/bin/bash read -p "Enter a string: " string count=$(echo "$string" | tr -cd 'aeiouAEIOU' | wc -c) echo "Number of vowels: $count"
This uses <code>tr</code> to delete all characters except vowels, then counts characters with <code>wc -c</code>.
Complexity: O(n) time, O(n) space
Time Complexity
The script processes each character once to check if it is a vowel, so time grows linearly with string length.
Space Complexity
Extra space is used to hold the extracted vowels temporarily, proportional to the number of vowels.
Which Approach is Fastest?
Using grep and wc is concise and fast for typical strings; the loop method is more manual and slightly slower.
| Approach | Time | Space | Best For |
|---|---|---|---|
| grep + wc | O(n) | O(n) | Quick and simple scripts |
| Loop + case | O(n) | O(1) | Environments without grep or wc |
| tr + wc | O(n) | O(n) | Simple character filtering |
Use
grep -o -i '[aeiou]' to easily extract vowels from any string in Bash.Forgetting to use the
-o option with grep causes the entire string to be matched once, not each vowel separately.