Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

count specific word in line in bash

Tags:

bash

i have variable such as "1,2,3,4"

i want to count of commas in this text in bash

any idea ?

thanks for help

like image 439
soField Avatar asked Feb 02 '10 09:02

soField


People also ask

How do I count words in a string in bash?

Using wc command. wc command is used to know the number of lines, word count, byte and characters count etc. Count the number of words using wc -w. Here, “-w” indicates that we are counting words.

How do you count words in a line?

To count the number of words in only part of your document, select the text you want to count. Then on the Tools menu, click Word Count. Just like the Word desktop program, Word for the web counts words while you type.

How do I count a specific word in Unix?

Using grep -c alone will count the number of lines that contain the matching word instead of the number of total matches. The -o option is what tells grep to output each match in a unique line and then wc -l tells wc to count the number of lines. This is how the total number of matching words is deduced.

How do I count a specific word in Vim?

For counting the number of words, press g, then Ctrl+g. This will display the number of words currently in the buffer.


2 Answers

This will do what you want:

echo "1,2,3" | tr -cd ',' | wc -c
like image 139
Alok Singhal Avatar answered Sep 29 '22 11:09

Alok Singhal


Off the top of my head using pure bash:

var="1,2,3,4"
temp=${var//[^,]/}
echo ${#temp}
like image 35
SiegeX Avatar answered Sep 29 '22 10:09

SiegeX