change directory (cd) but by replacing a part of the path only

Not sure if it is possible, but i seem to remember from my old days using AIX it was possible to change my path by just saying which part of the path needed to be replaced by something else. For instance, say i have two paths:

/etc/application-2.0.1/options/default

and

/etc/application-1.0.8/options/default

that i could switch from folder 1 to 2 using a command like

cd /2.0.1/1.0.8/

which would replace, in the path, the string 2.0.1 to 1.0.8. Obviously this does not work for me now. But is there a way to do this?


If you use zsh as shell you can just enter cd 1.0.8 2.0.1.


I have used (and missed) this feature myself. It depends on which flavor and/or release of *nix you are using. If you use bash, here is a handy way to extend the builtin cd to include this functionality. Put this in your .bashrc (or to test paste it in your bash shell and hit enter).

function cd() { if [ $# -eq 2 ]; then builtin cd "${PWD/$1/$2}"; else builtin cd "$1"; fi }

This should work in bash on ubuntu 10.04 : cd ${PWD/old/new}. Basically this replaces first occurrence of old in your present working directory with new. 2 examples below.

Example 1

ing02741@hoster:~$ cd /home/ing02741/Videos/
ing02741@hoster:~/Videos$ cd ${PWD/ing02741/koushik}
ing02741@hoster:/home/koushik/Videos$ 

Example 2

ing02741@hoster:~/src/cdtest$ mkdir dir-v1.0.1 dir-v2.2.2 dir-v3.0.7
ing02741@hoster:~/src/cdtest$ mkdir dir-v1.0.1/ind dir-v2.2.2/ind dir-v3.0.7/ind
ing02741@hoster:~/src/cdtest$ cd dir-v1.0.1/ind/
ing02741@hoster:~/src/cdtest/dir-v1.0.1/ind$ cd ${PWD/1.0.1/2.2.2}
ing02741@hoster:~/src/cdtest/dir-v2.2.2/ind$ 

Borrowing on idea of sepp2k's answer, you could make a function like this

function mycd { cd ${PWD/$1/$2} }

and then use something like mycd 2.0.1 1.0.8 to switch.


You're probably remembering history expansion. I don't know what was available in your shell on AIX, but one way to do this in bash is ^2.0.1^1.0.8.

History expansion is less useful with shells like bash and zsh that have powerful command line editing. You can use arrow keys to recall previous commands, and Alt+. to insert the last word of the previous command (press it twice to reach the command before that and so on).


If you are a vi fan you could enable the vi mode in your shell (bash set -o vi for example) and use the command mode of vi ...

Or you could do crazy history expansion (tested in zsh, perhaps in bash as well):

$ cd /etc/application-1.0.8/options/default
cd: no such file or directory: /etc/application-1.0.8/options/default

$ !!:s/1.0.8/2.0.1/
cd /etc/application-2.0.1/options/default
cd: no such file or directory: /etc/application-2.0.1/options/default