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
"Where there is a shell, there is a WAY !!" Blog on Awk, Sed, BASH ones liners and scripts.
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
© Jadu Saikia www.UNIXCL.com
4 comments:
Thanks for this. It's always nice to see a few different ways of doing something.
how about echo -n $VAR | wc -m?
@Tyzoid D, thanks a lot.
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
Post a Comment