Count the number of times a character appears in a string

Asked

Viewed 2,433 times

3

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

For example: How many times the character / appears in the string down below?

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

That one string will be within a variable $v_dir_relatorio.

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

4 answers

2

By the way using Perl:

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

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

2

echo $v_dir_relatorio | grep -o / | wc -l    
  1. echo to pass something to the pipeline, in this case $v_dir_relatorio
  2. grep to find a pattern, in this case the character '/'. The option -o prints each match found in a row.
  3. wc to count. With -l it counts the number of lines, which matches the amount of 'Matches' found.
  • Thank you Genos! It worked perfectly, but I can only mark as a solution a reply, thanks!

2

  • Thank you very much Osmar! Thanks!

2


Another alternative is to remove the characters you don’t want by 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

  • Thank you very much stderr, exactly what I needed! o/

Browser other questions tagged

You are not signed in. Login or sign up in order to post.