How to find relative path given two absolute paths?

后端 未结 5 1449
天命终不由人
天命终不由人 2020-12-19 08:31

Given two absolute paths, e.g.

  • /a/path/to/a
  • /a/path/to/somewhere/else

How can I get a relative path from one

5条回答
  •  隐瞒了意图╮
    2020-12-19 08:50

    Find the longest common path (in this case, /a/path/to) and delete it from both absolute paths. That would give:

    • /a
    • /somewhere/else

    Now, replace each path component in the starting path with ../ and prepend the result to the destination path. If you want to go from directory else to directory a, that would give you:

    ../../a
    

    If you want to go the other way, you'd instead have:

    ../somewhere/else
    

提交回复
热议问题