Unix / Linux: Count Occurrences of Character in String

Objective: Count the number of occurrences of a single character in a string.

Counting of a single character can be accomplished using a combination of grep and wc or by just using bash parameter expansion. Let’s say we want to count the number of ‘l’ from the following string.

$ str1="hello world. HELLO WORLD."

To count using grep, we will need to use the “-o” option – this will print each matched part on a separate output line.

$ echo $str1 | grep -o "l"
l
l
l

Now, to count the number of lines, we will need to use the wc utility.

$ echo $str1 | grep -o "l" | wc -l
3

You can also use bash parameter expansion to get the same result.

$ c=${str1//[^l]}
$ echo ${#c}
3

If you would like to do a case-insensitive search, or to count occurrences of both ‘l’ and ‘L’, then you will need to use the following syntax.

$ echo $str1 | grep -o "[l|L]" | wc -l
6

Again, you can do this using bash parameter expansion.

$ c=${str1//[^l|L]}
$ echo ${#c}
6

For multi-line strings, you can use grep and wc.

$ str2="hello world.\nHELLO WORLD."
$ echo -e "$str2" | grep -o "[l|L]" | wc -l
6

ibrahim = { interested_in(unix, linux, android, open_source, reverse_engineering); coding(c, shell, perl, php, python, java, javascript, nodejs, angular, react); plays_on(xbox, ps4); linux_desktop_user(true); }