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

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


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.


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 }

Tags:

Bash