Search code examples
shellcd

generate a path to go backward a given path


Assuming I have the following relative path:

MY_PATH := first/second/third

I am searching for a preferably short shell command to achieve the following:

MY_NEW_PATH := ../../..

How to do this?


Solution

  • $ MY_PATH=first/second/third
    $ sed -e 's#[^/]\+/\?#../#g' <<<"$MY_PATH"
    ../../../
    

    The easiest way to get that path without the trailing slash is just to remove it.

    $ MY_PATH=first/second/third
    $ cdup=$(sed -e 's#[^/]\+/\?#../#g' <<<"$MY_PATH")
    $ echo "$cdup"
    ../../../
    $ echo "${cdup%/}"
    ../../..
    

    You could also use something like this (which generates an uglier, but still valid, path):

    $ MY_PATH=first/second/third
    $ sed -e 's#[^/]\+/\?#./.#g' <<<"$MY_PATH"
    ./../../.
    

    There might be a better alternative to get a trailing-slash-less path but I'd have to think about it more.