Nandakumar
Content Network

You are not logged in.
Click here to login.

Some part of this library is not public. You must register to get exclusive access. If you are already registered, click here to login.


Shell Programming >> 2017

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

By | | License: proprietary


Code
#!/bin/sh

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.


shell sh bash linux gnu unix script programming command-line
Shell Script to Find the Vowels, Consonants and Numbers in a String | Nandakumar Content Network
Copyright © 2015, 2016, 2017 Nandakumar Edamana.