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.

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

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

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

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.

Again, you can do this using bash parameter expansion.

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

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