4

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
  • 51
  • 1
  • 3
  • 4
  • `sed` and `wc` could work. – user2864740 Dec 30 '15 at 20:02
  • > grep -o "." << – 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

4 Answers4

6

Looking for character l in $STRING:

echo $STRING| grep -o l | wc -l
Gerard Rozsavolgyi
  • 4,484
  • 4
  • 32
  • 38
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
  • 17,923
  • 2
  • 22
  • 40
0
echo "Hello" | tr -cd "l" | wc -c

Trim delete compliment of "l"; count characters.

Qeebrato
  • 111
  • 5
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