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
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
sedandwccould work.grep -o "\."insteadgrep -o "some_string" filename | wc -lOR if checking based on a variable of ${string}, you would run the following...echo ${string} | grep -o "some_string" | wc -l