Count occurrences of a char in a string using Bash

前端 未结 7 1648
臣服心动
臣服心动 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:46

    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"
    

提交回复
热议问题