Count char occurrences in a string using Bash

I need to count the number of char occurrences in a string using Bash.

In the following example, when char is (for example) t , it echo has the correct number of occurrences of t in var , but when the character is a comma or semicolon, it prints zero:

 var = "text,text,text,text" num = `expr match $var [,]` echo "$num" 
+82
bash shell sh
May 21 '13 at 20:57
source share
5 answers

I would use the following awk command:

 string="text,text,text,text" char="," awk -F"${char}" '{print NF-1}' <<< "${string}" 

I split the string into $char and print the number of fields received minus 1.

If your shell does not support the <<< operator, use echo :

 echo "${string}" | awk -F"${char}" '{print NF-1}' 
+80
May 21 '13 at 9:05
source share

you can, for example, delete all other characters and calculate what remains, for example:

 var="text,text,text,text" res="${var//[^,]}" echo "$res" echo "${#res}" 

will print

 ,,, 3 

or

 tr -dc ',' <<<"$var" | awk '{ print length; }' 

or

 tr -dc ',' <<<"$var" | wc -c #works, but i don't like wc.. ;) 

or

 awk -F, '{print NF-1}' <<<"$var" 

or

 grep -o ',' <<<"$var" | grep -c . 

or

 perl -nle 'print s/,//g' <<<"$var" 
+84
May 21 '13 at 21:19
source share

You can do this by combining the tr and wc commands. For example, to count e in the line referee

 echo "referee" | tr -cd 'e' | wc -c 

Exit

 4 

Explanations: The tr -cd 'e' command deletes all characters other than 'e', ​​and the Command wc -c counts the remaining characters.

Several input lines are also suitable for this solution, for example, the command cat mytext.txt | tr -cd 'e' | wc -c cat mytext.txt | tr -cd 'e' | wc -c cat mytext.txt | tr -cd 'e' | wc -c can read e in mytext.txt , even if the file can contain many lines.

+37
Dec 13 '16 at 10:49
source share

awk works well if you have a server

 var="text,text,text,text" num=$(echo "${var}" | awk -F, '{print NF-1}') echo "${num}" 
+1
Jun 02 '14 at 17:15
source share

I would suggest the following:

 var="any given string" N=${#var} G=${var//g/} G=${#G} (( G = N - G )) echo "$G" 

No call to any other program

0
Jan 24 '19 at 4:00
source share



All Articles