I have a string in bash $str.
str="ayushmishraalightayushas"
I want to find no of times the letter 'a' occured in the string.
I have a string in bash $str.
str="ayushmishraalightayushas"
I want to find no of times the letter 'a' occured in the string.
This can be accomplished using grep -o
plus wc
:
$ echo "ayushmishraalightayushas" | grep -o 'a' | wc -l
5
As the first grep -o
shows:
$ echo "ayushmishraalightayushas" | grep -o 'a'
a
a
a
a
a
because the -o
option of grep does:
-o, --only-matching
Print only the matched (non-empty) parts of a matching line, with each such part on a separate output line.
and then it is just a matter of counting the number of lines with the wc -l
command.
This awk one-liner is simplest I believe to get this count without needing multiple piped commands:
str='ayushmishraalightayushas'
awk -F a '{print NF-1}' <<< "$str"
5