Bash: How to Count Number of Characters in String


Often you may want to use Bash to count the number of characters in a particular string.

You can use the following methods to do so:

Method 1: Count Total Characters in a String

echo ${#my_string}

This particular example will return the total number of characters in the string variable named my_string.

Method 2: Count Occurrences of Specific Character in String

 grep -o "e" <<<"$my_string" | wc -l

This particular example will return the total number of times the character “e” occurs in the string variable named my_string.

Method 3: Count Occurrences of Several Specific Characters in String

 grep -o -E "e|a" <<<"$my_string" | wc -l

This particular example will return the total number of times the characters “e” and “a” occurs in the string variable named my_string.

The following examples show how to use each method in practice.

Example 1: Count Total Characters in a String

We can use the following syntax to create a string variable named my_string and then count the total number of characters in it:

my_string="I hope you have a great day"
echo ${#my_string}

The following screenshot shows how to use this syntax in practice:

Bash count characters in string

This returns a value of 27, which tells us that there are 27 total characters in the string.

Note: Spaces count as characters.

Example 2: Count Occurrences of Specific Character in a String

We can use the following syntax to create a string variable named my_string and then count the total number of times the letter “e” appears in the string:

my_string="I hope you have a great day"
grep -o "e" <<<"$my_string" | wc -l

The following screenshot shows how to use this syntax in practice:

Bash count specific characters in string

This returns a value of 3, which tells us that the letter “e” occurs 3 times in the string.

Example 3: Count Occurrences of Several Specific Characters in a String

We can use the following syntax to create a string variable named my_string and then count the total number of times the letter “e” and “a” appears in the string:

my_string="I hope you have a great day"
grep -o -E "e|a" <<<"$my_string" | wc -l

The following screenshot shows how to use this syntax in practice:

Bash count occurrences of several specific characters in string

This returns a value of 7, which tells us that the letters “e” and “a” occur a total of 7 times in the string.

Related Tutorials

The following tutorials explain how to perform other common tasks in Bash:

Bash: How to Count Number of Unique Lines in File
Bash: How to List All Files in Folder by Size
Bash: How to List All Files in Folder Without Extension
Bash: How to List All Files Matching a Specific Pattern

Leave a Reply