Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

finding substrings question 1

Status
Not open for further replies.

Mthales

Technical User
Feb 27, 2004
1,181
0
0
GB
This question will probably be very easy for all you experts but as a newbey I've been driven mad by it.

I have a ksh script and within this I have two variables that contain directory paths SB_HOME and CD. What I want to do is test that CD is under SB_HOME and then fill a third variable BASE with the value of the directory under SB_HOME that contains CD.

For example, if SB_HOME is "/home/mthales/workspace" and CD is "/home/mthales/workspace/Testing/src/level1/sub" then I want BASE to become "/home/mthales/workspace/Testing"

I've got the line if [ -n "$(echo "${CD}" | grep "${SB_HOME}")" ]; then to be able to test that CD is under SB_HOME but I can't get the extraction of the sub string from CD to work. So how could I go about this?

Thanks very much for any help
M

Trainee Chocolate Management Executive.
 
This should do the trick if you are using ksh:

Code:
#!/bin/ksh
SB_HOME="/home/mthales/workspace"
CD="/home/mthales/workspace/Testing/src/level1/sub"

if [[ "${CD}" == "${SB_HOME}"* ]]
then
        # Get the subdirectory only
        SUBDIR=${CD#${SB_HOME}/}
        print "SUBDIR is $SUBDIR"
        # Append the first level of the subdirectory to SB_HOME
        BASE=${SB_HOME}/${SUBDIR%%/*}
        print "BASE is ${BASE}"
else
        print "Error: ${CD} is not in ${SB_HOME}"
        exit 1
fi

Annihilannic.
 
Thank you very much for such a quick reply - it works perfectly. Also I really appreciate that you've commented it and kept it simple enough for even me to understand what it's doing :)

Thank you again.
M

Trainee Chocolate Management Executive.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top