Number of specific char in a string.

I wish to compute the number of dot chars in a string.
Example:
VAR="aaaa.bbbbb.cccc"

I try the shortest command to solve this test.

Thanks in advance for your help.
Regards,

  Giovanni

echo $VAR|awk '{print gsub("\.",0)}'

As far as I am aware the gsub trick only works with gawk.
The AT&T version (awk/nawk) does not return the number
of substitutions. Nor is this required by POSIX or Single
UNIX Specifications.

Another way of achieving the required result is:

 echo $VAR | tr -c -d '.' | wc -c
  • Finnbarr

The gsub() function exists in the freely available awks including POSIX awk, nawk and gawk.

Nice solution though.

Yes, gsub() exists in all versions of g/n/awk. However, gawk
is the only version where the man page states that the
function returns the number of substitutions made.

Man pages for the other versions of awk are silent on this
issue. POSIX.1:2003 does not mandate it. This being the
case, one cannot rely on this behavour in portable code.

  • Finnbarr

Thanks!:slight_smile:

On my OS (Aix v. 5.1) the command echo $VAR|awk '{print gsub("\.",0)}' returns always 1 if the VAR string contains or not a dot character.

echo $VAR|awk '{print gsub("\.",0)}' works correctly.

Giovanni

echo ${VAR}|awk -F. '{print NF-1}'

fpmurphy will probably win the prize for shortest command and that is what the OP requested. But it uses two external processes. linuxpenguin has a clever solution that uses only one external process at the cost of being a tad longer. That is probably the best solution.

But I couldn't resist trying this with zero external processes and I think I got it. Here is my test script --

#! /usr/bin/ksh
while read string?"enter string - " ; do
      ndots=0
      xstring=$string
      while [[ $xstring != ${xstring%.*} ]] ; do
            ((ndots=ndots+1))
            xstring=${xstring%.*}
      done
      echo "$string has $ndots dots"
done
exit 0

Despite the fact that this requires several lines, it will win in speed because no fork() or exec() is required. If this is something in an inner loop of a lengthy script the savings can add up. But if you're just validating user input it's probably not worth the effort.