Friday, September 9, 2011

Bash Recipes Part 2 - Process a string character by character

For splitting a string character by character, or doing any sort of operation per each character use the following code snippet

safeer@penguinpower:~$ NAME=safeer;for((i=0;i<${#NAME};i++)); do echo ${NAME:$i:1}; done

s

a

f

e

e

r

${#NAME} is the length of the variable $NAME

${NAME:$i:1} - This is a bash parameter substitution technique. U can extract a substring of a variable by using the syntax "${parameter:offset:length}" - This expands to up to "length" characters of parameter starting at the character specified by "offset" - The offset starts at zero.


In our case we use $i as the offset and in every iteration of the for loop we increment $i from zero to length of the string minus one ( which is the list of offsets for every single character in the string ). The length of substring is always 1 ( hence single character ). So ultimately per every iteration we extract one character from the string advancing from the beginning to the end.

Now if you want to extract the character in the reverse order, start the index from -1 and down to negative of string length.

safeer@penguinpower:~$ A=safeer;for((i=-1;i>=-${#A};i--)); do echo ${A:$i:1}; done

r

e

e

f

a

s


No comments:

Post a Comment