2

This question already has an answer here:

How do I use a command to convert an absolute path to a path relative to the current working directory?

marked as duplicate by muru, Sparhawk, Thomas, peterh, msp9011 Jun 3 at 6:40

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

  • 1
    so we should assume that the absolute path in-hand refers to the current directory or a subdirectory thereof? In what form is the absolute path: a variable? a line in a file? stdin? other? – Jeff Schaller May 30 at 17:45
8

Use

realpath --relative-to=. /absolute/path

More about it here.

  • 3
    I would also mention realpath's -s option, which prevents the expansion of symbolic links. Useful if the argument is a symlink and you don't want it resolved. – fra-san May 30 at 19:28
1

Just for the fun of 'rolling your own"

here=/dir1
there=/dir1/dir4/dir5/my.file
root=""
if [ ! -z $(grep "^$here" <<<$there) ]; then
    root="./"
else while [ -z $(grep  "^$here" <<<$there) ]; do
    here=${here%/*}
    root=${root}../
    done
fi
echo $root$(sed "s|^$here/||g" <<<$there)

./dir4/dir5/my.file

and for

here=/dir1/dir2/dir3

../../dir4/dir5/my.file

Not the answer you're looking for? Browse other questions tagged or ask your own question.