Count occurrences of a char in a string using Bash

前端 未结 7 1584
臣服心动
臣服心动 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"
    
    0 讨论(0)
  • 2020-11-27 11:46

    awk works well if you your server has it

    var="text,text,text,text" 
    num=$(echo "${var}" | awk -F, '{print NF-1}')
    echo "${num}"
    
    0 讨论(0)
  • 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}'
    
    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 2020-11-27 11:59

    Building on everyone's great answers and comments, this is the shortest and sweetest version:

    grep -o "$needle" <<< "$haystack" | wc -l

    0 讨论(0)
  • 2020-11-27 11:59

    I Would suggest the following:

    var="any given string"
    N=${#var}
    G=${var//g/}
    G=${#G}
    (( G = N - G ))
    echo "$G"
    

    No call to any other program

    0 讨论(0)
提交回复
热议问题