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,273
  • 3
  • 11
  • 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
  • 252,262
  • 96
  • 511
  • 570
1

One way:

echo ayushmishraalightayushas | grep -o a | wc -l
Adam Siemion
  • 15,064
  • 6
  • 51
  • 88
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
  • 713,503
  • 59
  • 514
  • 593