Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

BASH: Path difference between two paths?

Say I have the paths

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

How do I get the below?

e/f
like image 925
Pithikos Avatar asked Sep 08 '14 13:09

Pithikos


People also ask

What is the difference between path and path?

1) PATH and Path are the same since Windows environment variables are case insensitive (File paths in Windows environment not case sensitive?). 2) Windows use Path to locate executables that are not located in the "current folder".

What is a relative path in bash?

Relative path is defined as path related to the present working directory(pwd).

What is absolute path in bash?

An Absolute Path is a full path specifying the location of a file or directory from the root directory or start of the actual filesystem. Example: /home/javatpoint/Desktop/CollegeStudent. An Absolute path of any directory always starts with a slash (/) representing the directory root.

How do you change absolute path to relative path?

Simple: realpath --relative-to=$absolute $current .


1 Answers

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
like image 76
fedorqui 'SO stop harming' Avatar answered Oct 05 '22 08:10

fedorqui 'SO stop harming'