I need to count the number of occurrences of a char in a string using Bash.
In the following example, when the char is (for example) t
, it
You can do it by combining tr
and wc
commands. For example, to count e
in the string referee
echo "referee" | tr -cd 'e' | wc -c
output
4
Explanations: Command tr -cd 'e'
removes all characters other than 'e', and Command wc -c
counts the remaining characters.
Multiple lines of input are also good for this solution, like command cat mytext.txt | tr -cd 'e' | wc -c
can counts e
in the file mytext.txt
, even thought the file may contain many lines.
*** Update ***
To solve the multiple spaces in from of the number (@tom10271), simply append a piped tr command:
tr -d ' '
For example:
echo "referee" | tr -cd 'e' | wc -c | tr -d ' '