Saturday, February 7, 2009

substring operation with bash

You can get a substring (substr) value of an string variable as following in bash.
Syntax is simple ${VARIABLE_NAME:start:length}

let's assume we have a string variable called mystring and it has the value "test".

mystring="test"

If you want to access first character of the string you can use following statement.
c=${mystring:0:1}

now c value contains "t" character.

c=${mystring:2:2}

Now c contains "st" substring.

Hint: You can calculate the length of a string value as follows.

${#mystring}

No comments: