Nandakumar Edamana
Share on:
@ R t f
Section: shell-script

Shell Script to Count the Vowels, Consonants and Numbers in a String

Following in an example shell program to find the number of occurrences of English vowels, consonants and numbers in a string. It accepts a line of text from the user and then uses a combination of grep (a pattern matching program) and wc (a program to words, lines, etc.) to count the characters we are interested in.


echo -n "Enter a line of text: "
read string

numCount=$(echo $string | grep -o "[0-9]" | wc --lines)
vowCount=$(echo $string | grep -o -i "[aeiou]" | wc --lines)
consCount=$(echo $string | grep -o -i "[bcdfghjklmnpqrstvwxyz]" | wc --lines)

echo "The given string has $vowCount vowels, $consCount consonants and $numCount numbers in it."

The utility grep is used to perform a match against the string. We run grep three times with three expressions (one for numbers, one for vowels and one for consonants.

The output of grep is piped to wc, which will count the matches. The -o option is used with grep to print the matched characters only. Otherwise, grep would print the entire string, with the matches in a different colour. But this would cause wc to count all the lines in the string. If -o is used, the matched characters will be printed line by line, and wc will count them (please note that these printings are not visible on the screen, as they are read by our script internally).

The -i option is used with grep to make the search case-insensitive.

Click here to read more like this. Click here to send a comment or query.