Say I have the paths
a/b/c/d/e/f
a/b/c/d
How do I get the below?
e/f
Say I have the paths
a/b/c/d/e/f
a/b/c/d
How do I get the below?
e/f
You can strip one string from the other with:
echo "${string1#"$string2"}"
See:
$ string1="a/b/c/d/e/f"
$ string2="a/b/c/d"
$ echo "${string1#"$string2"}"
/e/f
From man bash
-> Shell parameter expansion:
${parameter#word}
${parameter##word}
The word is expanded to produce a pattern just as in filename expansion. If the pattern matches the beginning of the expanded value of parameter, then the result of the expansion is the expanded value of parameter with the shortest matching pattern (the ‘#’ case) or the longest matching pattern (the ‘##’ case) deleted.
With spaces:
$ string1="hello/i am here/foo/bar"
$ string2="hello/i am here/foo"
$ echo "${string1#"$string2"}"
/bar
To "clean" multiple slashes, you can follow Roberto Reale's suggestion and canonicalize the paths with readlink -m
to allow comparison with strings with the same real path up:
$ string1="/a///b/c//d/e/f/"
$ readlink -m $string1
/a/b/c/d/e/f
Another solution (from this other related post) is:
$ realpath -m --relative-to=a/b/c/d a/b/c/d/e/f
e/f
It properly handles spaces (quote the path in that case) and multiple slashes.
The option -m
is simply here to avoid errors when either path doesn't exist.
© 2022 - 2024 — McMap. All rights reserved.