Count occurrences of a char in a string using Bash

前端 未结 7 1590
臣服心动
臣服心动 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 12:05

    You can do it by combining tr and wc commands. For example, to count e in the string referee

    echo "referee" | tr -cd 'e' | wc -c
    

    output

    4
    

    Explanations: Command tr -cd 'e' removes all characters other than 'e', and Command wc -c counts the remaining characters.

    Multiple lines of input are also good for this solution, like command cat mytext.txt | tr -cd 'e' | wc -c can counts e in the file mytext.txt, even thought the file may contain many lines.

    *** Update ***

    To solve the multiple spaces in from of the number (@tom10271), simply append a piped tr command:

     tr -d ' '
    

    For example:

    echo "referee" | tr -cd 'e' | wc -c | tr -d ' '
    
    0 讨论(0)
提交回复
热议问题