Search code examples
bashshellsh

Count occurrences of a char in a string using Bash


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 echos 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"

Solution

  • I would use the following awk command:

    string="text,text,text,text"
    char=","
    awk -F"${char}" '{print NF-1}' <<< "${string}"
    

    I'm splitting the string by $char and print the number of resulting fields minus 1.

    If your shell does not support the <<< operator, use echo:

    echo "${string}" | awk -F"${char}" '{print NF-1}'