Is there a bash shortcut for traversing similar directory structures?

Posted by Steve Weet on Stack Overflow See other posts from Stack Overflow or by Steve Weet
Published on 2009-09-06T19:29:06Z Indexed on 2010/04/25 6:13 UTC
Read the original article Hit count: 352

Filed under:
|
|
|

The Korn shell used to have a very useful option to cd for traversing similar directory structures e.g. given the following directorys

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

Then if you were in the /home/sweet.... directory then you could change to the equivalent directory in andy's structure by typing

cd sweet andy

So if ksh saw 2 arguments then it would scan the current directory path for the first value, replace it with the second and cd there. Is anyone aware of similar functionality in bash.

EDIT 1

Following on from Michal's excellent answer I have now created the following bash function called scd (For Sideways cd)

function scd {
  cd "${PWD/$1/$2}"
}

EDIT 2

Thanks to @digitalross I can now reproduce the ksh functionality exactly with the code from below (With the addition of a pwd to tell you where you have changed to)

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

© Stack Overflow or respective owner

Related posts about shell-scripting

Related posts about bash