Signup/Sign In
Ask Question
Not satisfied by the Answer? Still looking for a better solution?

How to count the number of a specific character in each line?

I was wondering how to count the number of a specific character in each line by some text processing utilities?

For example, to count " in each line of the following text

"hello!" 
Thank you!


The first line has two, and the second line has 0.

Another example is to count ( in each line.
by

1 Answer

Bharatv4tg1
Using tr ard wc:
function countchar()
{
while IFS= read -r i; do printf "%s" "$i" | tr -dc "$1" | wc -m; done
}

Usage:
$ countchar '"' <file.txt  #returns one count per line of file.txt
1
3
0

$ countchar ')' #will count parenthesis from stdin
$ countchar '0123456789' #will count numbers from stdin

Login / Signup to Answer the Question.