Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Counting the number of dots in a string

Tags:

bash

How do I count the number of dots in a string in BASH? For example

VAR="s454-da4_sd.fs_84-df.f-sds.a_as_d.a-565sd.dasd"

# Variable VAR contains 5 dots
like image 554
Charlie Avatar asked Aug 14 '12 13:08

Charlie


People also ask

How do you count the number of dots on a string in Python?

str. count('\. ')

How many dots are in a string C#?

Cut string and display three dots : String Util « Data Types « C# / C Sharp.


2 Answers

You can do it combining grep and wc commands:

echo "string.with.dots." | grep -o "\." | wc -l

Explanation:

grep -o   # will return only matching symbols line/by/line
wc -l     # will count number of lines produced by grep

Or you can use only grep for that purpose:

echo "string.with.dots." | grep -o "\." | grep -c "\."
like image 54
Rostyslav Dzinko Avatar answered Sep 21 '22 06:09

Rostyslav Dzinko


VAR="s454-da4_sd.fs_84-df.f-sds.a_as_d.a-565sd.dasd"
echo $VAR | tr -d -c '.' | wc -c

tr -d deletes given characters from the input. -c takes the inverse of given characters. together, this expression deletes non '.' characters and counts the resulting length using wc.

like image 24
perreal Avatar answered Sep 22 '22 06:09

perreal