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 echo
s the correct number of occurrences of t
in var
, but when the character is comma or semicolon, it prints out zero:
var = "text,text,text,text"
num = `expr match $var [,]`
echo "$num"
you can for example remove all other chars and count the whats remains, like:
var="text,text,text,text"
res="${var//[^,]}"
echo "$res"
echo "${#res}"
will print
,,,
3
or
tr -dc ',' <<<"$var" | awk '{ print length; }'
or
tr -dc ',' <<<"$var" | wc -c #works, but i don't like wc.. ;)
or
awk -F, '{print NF-1}' <<<"$var"
or
grep -o ',' <<<"$var" | grep -c .
or
perl -nle 'print s/,//g' <<<"$var"