petr
petr

Reputation: 51

Determine the number of characters in a variable

How can I determine the number of characters in a variable?

FOO="blabla.bla.blabla.bla."
--check--
echo $FOO # 4 dot

FOO="..bla.bla.bla.blabla.bla."
--check--
echo $FOO # 7 dot

Upvotes: 1

Views: 149

Answers (4)

ormaaj
ormaaj

Reputation: 6577

Strip the non-dots and count the length of the result.

 $ x=..bla.bla.bla.blabla.bla.
 $ _=${x//[^.]} count=${#_}; echo "$count"
7
 $ printf -v _ %s%n "${x//[^.]}" count; echo "$count"
7

Upvotes: 0

MeBa
MeBa

Reputation: 1

echo $FOO | tr -dc \\. | wc -c

Does that answer your question?

Upvotes: 0

Kent
Kent

Reputation: 195039

 awk -F. '{print NF-1}' <<<$FOO 

example:

kent$  FOO="blabla.bla.blabla.bla."   

kent$  awk -F. '{print NF-1}' <<<$FOO
4

kent$  FOO="..bla.bla.bla.blabla.bla."

kent$  awk -F. '{print NF-1}' <<<$FOO 
7

Upvotes: 0

hek2mgl
hek2mgl

Reputation: 157947

You should try this:

echo ${#FOO} 

${#VARIABLE_NAME} gives you the lenght of a string. Read (its on top of the page)

Upvotes: 1

Related Questions