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

5
  • sed and wc could work. Commented Dec 30, 2015 at 20:02
  • > grep -o "." <<<"hello.txt." | wc -l output returns 10, which is incorrect. Ideally this should return 2 Commented Dec 30, 2015 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 Commented Dec 30, 2015 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 Commented Dec 30, 2015 at 22:24
  • Does this answer your question? Count occurrences of a char in a string using Bash Commented Feb 16, 2021 at 20:59

5 Answers 5

7

Looking for character l in $STRING:

echo $STRING| grep -o l | wc -l
Sign up to request clarification or add additional context in comments.

Comments

1
echo "Hello" | tr -cd "l" | wc -c

Trim delete compliment of "l"; count characters.

Comments

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

Comments

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

1 Comment

Sorry, wrong output.
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.