Pithikos Pithikos - 11 months ago 76
Bash Question

BASH: Path difference between two paths?

Say I have the paths


How do I get the below?


Answer Source

You can strip one string from the other with:

echo "${string1#"$string2"}"


$ string1="a/b/c/d/e/f"
$ string2="a/b/c/d"
$ echo "${string1#"$string2"}"

From man bash -> Shell parameter expansion:



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"}"

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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download