A reader recently asked whether it was possible on Unix systems to count how many times a particular character appears on each line of text. “On Unix”, I answered, “not only is just about anything possible, but there are usually half a dozen ways to do it”.
Counting how many times a particular character appears on a line of text, while not exactly straightforward, is easily done. If you take advantage of awk’s ability to identify fields and its built-in field counter (NF), you can get very close. Tell awk the character in question is the field separator and it will happily count how many times it appears. You just have to account for fact that awk will report one more character than is actually included on each line. The string “ababa”, for example, would report three fields if “b” is interpreted as the field separator. Reducing each count by one, therefore, tells you how many b’s appear on the line.
Here’s a simple script that does this, asking first what character you want to count:
#!/bin/bash
echo -n "character to count> "
read char
echo -n "file> "
read file
if [ ! -f $file ]; then
echo "OOPS: No file named $file"
exit
fi
for n in `awk -F${char} '{print NF}' $file`
do
n=$(($n - 1))
echo $n
done
Similarly, if you want a count of how many times a character appears in a file, you can “scrunch” the file down to a single line by removing the linefeeds and avoid having to subtract one more than once.
$ cat myfile This is the start of a new era in the life of our members. We can choose to take a stand or we can hide in the shadows. $ cat myfile | tr -d "




