Sunday, June 8, 2008

Count particular character in a string - bash

Count particular character in a string - bash


$ string="unix bash script tutorial"

Now if I have to count the number of "i" s in the $string,

$ string="${string//[^i]/}"; echo ${#string}


$ echo $((`echo $string|sed 's/[^i]//g'|wc -m`-1))

-m (print the character counts, an wc option)

1 comment:

Karan Bohra said...

To determine the count of a char. in a given string we can do the following:

1. printf '%s\n' "$string" | tr -cd 'i' | wc -m

2. printf '%s\n' "$string" | perl -ple '$_ = tr/i//d'

3. printf '%s\n' "$string" | sed -e 's/[^i]//g;/i/!Q;s///' | wc -m

4. ( IFS="i"; set -f; set X $string; shift 2; echo "$#" )

We execute the step-4 in a subshell to ensure that changes to `super-globals',
like, "IFS", "set -f", "$#", do not corrupt the current settings.

N.B.: Some characters for which count is being determined, might be special and should be appropriately quoted, e.g., "^".

© Jadu Saikia