Calculate the number of vowels and consonants in a word
I want to calculate the number of vowels and consonants in a word in a shell script, but I'm not sure how I can run through the word. Can anyone help me? What I so far have is:
#!/bin/bash
echo 'Give a wor开发者_如何学God'
read word
case $word
in
a*|e*|i*|o*|u*)
vowels=&((klinker + 1 ))
;;
*)
consonants=&((medeklinker + 1 ))
;;
esac
echo $vowels
echo $consonants
Assuming you want to count the number of vowels and number of consonants, and that the shell is bash
, what about:
word=abstemiously
vowels=$(echo $word | sed 's/[^aeiou]//g')
consonants=$(echo $word | sed 's/[aeiou]//g')
echo "${#word} characters"
echo "${#vowels} vowels"
echo "${#consonants} consonants"
Output:
12 characters
5 vowels
7 consonants
You could compress the processing, and you could use tr
instead of sed
. There are also, in Bash 4.x at least, substitution operations in the shell that might be usable so you don't have to run an external program (such as tr
or sed
) at all. You also need to think what happens to punctuation, digits and spaces (generically, non-letters). Again, there are multiple ways to deal with such issues.
vowels=`echo $word | tr -cd 'aeiou' | wc -c`
just with bash:
letters=${word//[^[:alpha:]]/} # remove all whitespace, punctuation, etc
cnsnnts=${letters//[aeiou]/} # remove vowels
num_consonents=${#cnsnnts}
num_vowels=$(( ${#letters} - $num_consonents ))
#A very Simple Program to count vowels and consonants:
read word
v=`echo $word | tr -cd 'aeiou' | wc -c`
c=`echo $word | tr -cd 'bcdfghjklmnpqrstvwxyz' | wc -c`
echo "vowels = $v"
echo "consonants = $c"
精彩评论