5

Is there anyway to count number of times a character appears in a string in unix at command line.

eg: string="Hello" "l" this should return 2

string = "hello" "k" this should return 0

string = "hello" "H" this should return 0

Thanks

sunshine737
  • 61
  • 2
  • 3
  • 4
  • `sed` and `wc` could work. – user2864740 Dec 30 '15 at 20:02
  • > grep -o "." <<<"hello.txt." | wc -l output returns 10, which is incorrect. Ideally this should return 2 – sunshine737 Dec 30 '15 at 20:04
  • You are grepping for ".", which is a regular expression that matches any character. If you want to match the "dot" character, try `grep -o "\."` instead – Markku K. Dec 30 '15 at 20:13
  • `grep -o "some_string" filename | wc -l` OR if checking based on a variable of ${string}, you would run the following... `echo ${string} | grep -o "some_string" | wc -l` – IT_User Dec 30 '15 at 22:24
  • Does this answer your question? [Count occurrences of a char in a string using Bash](https://stackoverflow.com/questions/16679369/count-occurrences-of-a-char-in-a-string-using-bash) – Ingo Karkat Feb 16 '21 at 20:59

5 Answers5

7

Looking for character l in $STRING:

echo $STRING| grep -o l | wc -l
Gerard Rozsavolgyi
  • 4,834
  • 4
  • 32
  • 39
1
echo "Hello" | tr -cd "l" | wc -c

Trim delete compliment of "l"; count characters.

Qeebrato
  • 131
  • 7
0

Using Bash builtins with string hello and looking for the 'l' can be done with:

strippedvar=${string//[^l]/}
echo "char-count: ${#strippedvar}"

First you remove all characters different from l out of the string.
You show the length of the remaining variable.

The lettter in the substitution can be given by a var, as shown by this loop:

string=hello
for ch in a b c d e f g h i j k l m; do
    strippedvar=${string//[^$ch]/}
    echo "The letter ${ch} occurs ${#strippedvar} times"
done

OUTPUT:

The letter a occurs 0 times
The letter b occurs 0 times
The letter c occurs 0 times
The letter d occurs 0 times
The letter e occurs 1 times
The letter f occurs 0 times
The letter g occurs 0 times
The letter h occurs 1 times
The letter i occurs 0 times
The letter j occurs 0 times
The letter k occurs 0 times
The letter l occurs 2 times
The letter m occurs 0 times
Walter A
  • 19,067
  • 2
  • 23
  • 43
0

one liner answer

#for i in {a..l}; do str="hello";cnt=`echo $str| grep -o $i| wc -l`;echo $cnt| grep -v 0; done
1
1
2
0

Another variation to the solutions here

$ echo "hello" | grep -o . | uniq -c
      1 h
      1 e
      2 l
      1 o

I guess if you only wanted the one for "l".

$ echo "hello" | grep -o . | uniq -c | grep l
      2 l
Chai Ang
  • 474
  • 1
  • 6
  • 11