Count occurrences of a char in a string using Bash

前端 未结 7 1651
臣服心动
臣服心动 2020-11-27 11:26

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

7条回答
  •  夕颜
    夕颜 (楼主)
    2020-11-27 11:52

    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}'
    

提交回复
热议问题