Re: How to compute the relative path from the absolute paths?(in bash)

From: William (Reply_at_NewsGroup.Please)
Date: 10/28/05


Date: Fri, 28 Oct 2005 10:51:08 -0500


"William" <Reply@NewsGroup.Please> wrote in message
news:vtKdnTin2ahp2P_enZ2dnUVZ_s2dnZ2d@giganews.com...
> <PengYu.UT@gmail.com> wrote in message
> news:1130512627.131217.130650@f14g2000cwb.googlegroups.com...
> > Hi,
> >
> > Suppose I know the absolute paths of two directories? How can I compute
> > the simplest relative path between them?
> >
> > /home/dir1/b
> > /home/dir1/c
> >
> > I want the relative path of b to c is
> > ../b not ../../dir1/b, etc
>
> Just replace all the common path elements with
> a single '..' element. How you do it depends on
> your shell and which tools you want to use.
>
> In bourne shell you could set IFS to '/', then
> use set, shift and a for loop to compare each
> element until you find a difference.
>
> Once you find the difference, you replace
> everything up to that point with ../ and add
> all the leftover elements from your target
> path string.

Here's a sample (could use some input validation,
and you might want to restore IFS, etc.):

#!/bin/sh

# Wanted: Relative path from mainPath to target path
mainPath="/etc/dir1/dir2/dir3/b"
target="/etc/dir1/dir2/dir4/c"
relPath=''
IFS='/'
set -- $target
for elem in $mainPath
do
    case "$relPath" in
        "")
            [ "$1" = "$elem" ] || relPath="../$1"
            ;;
        *)
            relPath="$relPath/$1"
            ;;
    esac
    shift
done

echo "relPath = $relPath"



Relevant Pages

  • Re: bookmarks, hyperlinks and back
    ... Shift F5 jumps back to the point of last edit in the document. ... target text, using a hyperlink in order to reach that point. ... A section headed "Adjectives and Nouns" may need to be targeted from ... Nouns" section has been read the reader will then need to return to the ...
    (microsoft.public.word.formatting.longdocs)
  • Re: The late hit
    ... If you shift your weight properly toward the target, ... Do not move your arms at all ...
    (rec.sport.golf)
  • Re: Safe list assignment
    ... use warnings; ... sub safe_assign { ... my $targets = shift; ... for my $target { ...
    (perl.beginners)
  • Re: AR15 evaluation
    ... optics, ... to the target when the focal length is changed, so you have to zero it ... zoom point the cross hair point will shift. ... With a variable scope, when you get your ...
    (rec.crafts.metalworking)
  • How to do relpath implementation on 2.5
    ... When attempting to convert to a relative path and it is not possible for some reason, should that be an error or should it return the absolute path of the target? ... (ounc, origin) ... del target_list ...
    (comp.lang.python)