Tuesday, June 10, 2014

Advanced Unix shell scripting

Substrings

Often times a programmer needs to be able to get a substring from a variable at a given position. In unix you can use the expr command to do this with the substr parameter. 

Let's say that we have the text string "5283username$$2384/" and we want to get the text "username". To do this we need to read from position 5 for a length of 8. The parameters for substr are the input string, the starting position, and the length.

See the following example: 

INPUT="5283username$$2384/"

USER=`expr substr $INPUT 5 8`

echo "Sub: '$USER'"

No comments:

Post a Comment