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.
1 |
$ 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.
1 2 3 4 |
$ echo $str1 | grep -o "l" l l l |
Now, to count the number of lines, we will need to use the wc
utility.
1 2 |
$ echo $str1 | grep -o "l" | wc -l 3 |
You can also use bash parameter expansion to get the same result.
1 2 3 |
$ 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.
1 2 |
$ echo $str1 | grep -o "[l|L]" | wc -l 6 |
Again, you can do this using bash parameter expansion.
1 2 3 |
$ c=${str1//[^l|L]} $ echo ${#c} 6 |
For multi-line strings, you can use grep
and wc
.
1 2 3 |
$ str2="hello world.\nHELLO WORLD." $ echo -e "$str2" | grep -o "[l|L]" | wc -l 6 |