shell - Count occurrences of a char in a string using Bash -
i need count number of occurrences of char in string using bash.
in following example, when char (for example) t, echos correct number of occurrences of t in var, when character comma or semicolon, prints out zero:
var = "text,text,text,text" num = `expr match $var [,]` echo "$num"
you can use following bash script uses gnu grep , wc count chars:
needle="," var="text,text,text,text" number_of_occurrences=$(grep -o "$needle" <<< "$var" | wc -l)
Comments
Post a Comment