1

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
1

4 Answers 4

1

You should try this:

echo ${#FOO} 

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

2
  • count all characters? not only dots?
    – Kent
    Mar 7, 2013 at 21:25
  • Question was : How to determine the number of characters in a variable?
    – hek2mgl
    Mar 7, 2013 at 21:25
0
 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
0
0

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

Does that answer your question?

2
  • somehow I do not work :-(( ... if [ "$(echo $FOO | tr -dc \\. | wc -c)" -gt "1" ]; then ...
    – petr
    Mar 7, 2013 at 21:50
  • export FOO="..bla.bla.bla.blabla.bla."; if [ "$(echo $FOO | tr -dc \\. | wc -c)" -gt "8" ]; then echo "more"; else echo "less"; fi
    – MeBa
    Mar 7, 2013 at 22:08
0

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.