Below you can find some hints on how to count an occurrence of specific character in a file or in a string. Le’s say we have a string “Hello Bash”:
$ STRING="Hello Bash" $ echo $STRING Hello Bash
Using bash shell we can now count an occurrence of any given character. For example let’s count number of occurrences of a character l
:
$ echo $STRING | sed -e 's/\(.\)/\1\n/g' | grep l | wc -l 2
The sed
command first separates any given string to multiple lines. Where each line contains a single character:
$ echo $STRING | sed -e 's/\(.\)/\1\n/g' H e l l o B a s h
After that we can use grep
command to search only for specific characters. In this case we print only character l
:
$ echo $STRING | sed -e 's/\(.\)/\1\n/g' | grep l l l
What has left is to use wc -l
to simply count the lines:
$ echo $STRING | sed -e 's/\(.\)/\1\n/g' | grep l | wc -l 2
The same strategy can be also used to count a character occurrence in a file. The below bash shell command counts how many times a character l
appears in file /etc/services
:
$ cat /etc/services | sed -e 's/\(.\)/\1\n/g' | grep l | wc -l 9298
Yet, another alternative to count character occurrence is to use grep’s --only-matching
or -o
option to print only matching characters:
$ grep -o l /etc/services | wc -l 9298