1

I have a string in bash $str.

str="ayushmishraalightayushas"

I want to find no of times the letter 'a' occured in the string.

Ayush Mishra
  • 1,583
  • 3
  • 13
  • 13
  • And also http://stackoverflow.com/q/6741967/1983854, although the accepted answer is not to be followed. – fedorqui Nov 04 '13 at 13:49

3 Answers3

2

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.

fedorqui
  • 275,237
  • 103
  • 548
  • 598
1

One way:

echo ayushmishraalightayushas | grep -o a | wc -l
Adam Siemion
  • 15,569
  • 7
  • 58
  • 92
1

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
anubhava
  • 761,203
  • 64
  • 569
  • 643