Monday, September 29, 2008

Shell String Operations: How to get index of a substring in a string

The following commands returns the index of first occurance of character in a string
expr index $string $character
Please note that you can use a regular expression for character

Example:
stringZ=abcABC123ABCabc
echo `expr index "$stringZ" C`
# Retuns 6
echo `expr index "$stringZ" [c-z]`
# Returns 3

Shell String Operations: How to get length of a string

To get length of string in Unix shell, use the following command
${#varname}
where varname is name of the variable that contains the string
or you can also use command
expr length $varname

Example:
varname='Shoma'
expr length $varname
# Returns 5