Friday, March 7, 2008

Find String Length : BASH


Suppose:

$ VAR="Bash Scripting"

Now to find the length of the above string, I have found 3 different ways:

$ echo "${#VAR}"
14

$ expr length "$VAR"
14

$ echo $VAR | awk '{print length}'
14

4 comments:

Graham M said...

Thanks for this. It's always nice to see a few different ways of doing something.

Tyzoid D said...

how about echo -n $VAR | wc -m?

Jadu Saikia said...

@Tyzoid D, thanks a lot.

Karan Bohra said...

Here are a few more:

dc -e "[$VAR]Zp"

expr "$VAR" : '.*'

printf '%s\n' "$VAR" | sed '/./!d;s//\n/g;s///' | wc -l

# user-defined function
len() {
case ${1-} in '' ) echo 0; return;; esac
set -- "$1" '?' "/"
while case $1 in $2 ) break;; esac
do set -- "$1" "?$2" "/ $3"; done
set -- $3
echo "$#"
}
# ... and then use it as
len "$VAR"

Note that there's a subtle problem with the echo -n $VAR thing.
$VAR is either -ne or -en then the string length obtained is 0.
"printf" is the right way to go:
printf '%s' "$VAR" | wc -m

© Jadu Saikia www.UNIXCL.com