Count occurrences of a char in a string using Bash

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

    also check this out, for example we wanna count t

    echo "test" | awk -v RS='t' 'END{print NR-1}'
    

    or in python

    python -c 'print "this is for test".count("t")'
    

    or even better, we can make our script dynamic with awk

    echo 'test' | awk '{for (i=1 ; i<=NF ; i++) array[$i]++ } END{ for (char in array) print char,array[char]}' FS=""
    

    in this case output is like this :

    e 1
    s 1
    t 2
    

提交回复
热议问题