1

I have a path that is stored in a variable

$FULLPATH="/this/is/the/path/to/my/file.txt"

I also have another variable containing a partial path

$PARTIAL="/this/is/the/"

I want to remove the partial path from the full path so that I am left with:

path/to/my/file.txt

What's the best way to do this?

1
  • As is always the case, I solved it 30 seconds after posting. I am running the path through sed and removing the partial path... silly me Commented Apr 7, 2010 at 18:11

4 Answers 4

3

Use bash's # pattern matching operator:

${FULLPATH#${PARTIAL}}
Sign up to request clarification or add additional context in comments.

1 Comment

Is there a way to modify this so that there is an optional /? That way, if $PARTIAL doesn't have the /, it will still be removed?
3

Here's a little more detail to Mr. Klatchko's excellent answer:

$ FULLPATH="/this/is/the/path/to/my/file.txt"
$ PARTIAL="/this/is/the/"
$ echo ${FULLPATH#${PARTIAL}}
path/to/my/file.txt

Comments

1

If you're sure that $PARTIAL is an actual path:

result="${FULLPATH#$PARTIAL}"
result="${result#/}"

Comments

0
# echo $FULLPATH | sed 's#'"$PARTIAL"'##'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.