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
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.
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.
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.
For counting the number of words, press g, then Ctrl+g. This will display the number of words currently in the buffer.
This will do what you want:
echo "1,2,3" | tr -cd ',' | wc -c
Off the top of my head using pure bash:
var="1,2,3,4"
temp=${var//[^,]/}
echo ${#temp}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With