Count the number of times a character appears in a string

3

I need to count the number of times a character repeats in a string .

For example: How many times does the / character appear in the string below?

  

'/ file / program-files / test / dev / dev1 / Central.pdf.gz'

This string will be inside a $v_dir_relatorio variable.

I need the amount of bars to create a search logic for directories that the paths vary.

    
asked by anonymous 21.10.2016 / 17:18

4 answers

2

Another alternative is to remove the characters you do not want, using //[^\/] , after that just count the remaining characters:

v_dir_relatorio="'/file/program-files/teste/dev/dev1/Central.pdf.gz"
quantidade="${v_dir_relatorio//[^\/]}"

echo "${#quantidade}"  # 6

See DEMO

    
21.10.2016 / 18:09
2
echo $v_dir_relatorio | grep -o / | wc -l    
  • echo to pass something to the pipeline, in this case $v_dir_relatorio
  • grep to search for a pattern, in this case the '/' character. The -o option prints each 'match' found on a line.
  • wc to count. With -l it counts the number of lines, which matches the number of 'matches' found.
  • 21.10.2016 / 18:01
    2

    In shell script (bash) one of the alternatives can be:

    echo "/1/2/3/4" | grep -o '/' | wc -l
    

    For your case:

    v_dir_relatorio='echo "$CAMINHO" | grep -o '/' | wc -l'
    

    I found other valid answers at: link

        
    21.10.2016 / 18:06
    2

    Already using Perl:

    perl -nE 'say tr!/!!' <<< $v_dir_relatorio
    

    The command tr (which transforms the set of characters of the first group into the corresponding one of the second) returns the number of characters found.

        
    14.11.2016 / 17:40