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
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
Looking for character l in $STRING:
echo $STRING| grep -o l | wc -l
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
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
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