Is there a Bash shortcut for moving similar directory structures?

KornShell (ksh) had a very useful option cdfor moving similar directory structures; for example, using the following directories:

  • /home/sweet/dev/projects/trunk/projecta/app/models
  • /home/andy/dev/projects/trunk/projecta/app/models

Then, if you were in a directory /home/sweet..., then you can go to the equivalent directory in the andy structure by typing

cd sweet andy

So, if ksh sees 2 arguments, then it scans the current directory path for the first value, replaces it with the second and cd there. Does anyone know of similar functionality built into Bash? Or, if not, hacking to make Bash work the same?

+5
source share
3 answers

- :

  • - Michał Górny
  • ,
  • , , , : /canis/lupus/lupus/ /nicknames/Robert/Rob/

, .

cd () 
{ 
    local pwd="${PWD}/"; # we need a slash at the end so we can check for it, too
    if [[ "$1" == "-e" ]]
    then
        shift
        # start from the end
        [[ "$2" ]] && builtin cd "${pwd%/$1/*}/${2:-$1}/${pwd##*/$1/}" || builtin cd "$@"
    else
        # start from the beginning
        [[ "$2" ]] &&  builtin cd "${pwd/\/$1\///$2/}" || builtin cd "$@"
    fi
}

, cdX, , :

    /canis/lupus/lupus/specimen $ cdX lupus familiaris
    bash: cd: /canis/familiaris/lupus/specimen: No such file or directory

, "lupus" - , . , < -e .

    /canis/lupus/lupus/specimen $ cd -e lupus familiaris
    /canis/lupus/familiaris/specimen $

:

    /nicknames/Robert/Rob $ cdX Rob Bob
    bash: cd: /nicknames/Bobert/Rob: No such file or directory

. , .

    /nicknames/Robert/Rob $ cd Rob Bob
    /nicknames/Robert/Bob $

:

    /fish/fish/fins $ cd fish/fins robot/fins
    /fish/robot/fins $

, && || if... then... else... fi .

+5
cd "${PWD/sweet/andy}"
+3

No, but...

Mikal Gorni's replacement expression works great. To override the built-in cd command, do the following:

cd () {
  if [ "x$2" != x ]; then
    builtin cd ${PWD/$1/$2}
  else
    builtin cd "$@"
  fi
}
+2
source

All Articles