BASH: Path difference between two paths?
Asked Answered
T

2

9

Say I have the paths

a/b/c/d/e/f
a/b/c/d

How do I get the below?

e/f
Tonina answered 8/9, 2014 at 13:28 Comment(0)
H
18

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
Hinda answered 8/9, 2014 at 13:30 Comment(0)
E
0

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.

Evetteevey answered 17/8, 2023 at 12:54 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.