Reputation: 45
How can a find all the vowels for a word in bash?
grep -o "a" <<<$1 | wc l
This command finds only a
, and I want to find aeiou
.
For example:
car
I want the output to be 1
computer
I want the output to be 3
Upvotes: 0
Views: 2485
Reputation: 92854
bash approach with GNU expr
command:
Input variables:
v1="computer"
v2="car"
expr length "${v1//[^aeuoi]}"
3
expr length "${v2//[^aeuoi]}"
1
${v2//[^aeuoi]}
- replacing/removing all non-vowel characters
expr length STRING
- evaluates length of STRING
A more compatible variation would look like:
vowels="${v1//[^aeuoi]}"
echo "${#vowels}"
3
Upvotes: 1
Reputation: 133600
try:
echo "computer" | awk '{print gsub(/[aeiou]/,"")}'
So I am using echo
here to print the word, sending its standard output to awk
by pipe (|
) as standard input, then performing global substitution of letters a
,e
,i
, o
,u
with the empty string (""
).
Since gsub
returns the count of substitutions performed, it tells us how many vowel letters are present in the string.
Upvotes: 2
Reputation: 52291
You can combine -o
(only retain matches) with wc -l
and use a bracket expression to match all vowels:
$ grep -o '[aeiou]' <<< car | wc -l
1
$ grep -o '[aeiou]' <<< computer | wc -l
3
As a function (notice quotes around $1
to prevent word splitting and pathname expansion):
vowcount () { grep -o '[aeiou]' <<< "$1" | wc -l; }
Used like
$ vowcount alphabet
3
Upvotes: 3