Thursday, January 13, 2011

cd command with two arguments to do directory substitution

At some place I've worked in the past I had the ability to issue a CD command with two parameters. Extensive googling for this resulted in nothing, so I wrote this bash function to do it.

Using 'cd' in this mode will replace the first occurrence of the first parameter with the second parameter. The simplest use case is changing from classes to src directory when in a deep directory structure:

$ pwd
/home/rcs/project/src/com/xyz/custom/some/really/deep/path
$ cd src classes
$ pwd
/home/rcs/project/classes/com/xyz/custom/some/really/deep/path


function cd {
if [ -z $2 ]
then
builtin cd $1
else
builtin cd `echo $PWD | sed s/$1/$2/`
fi
}


It's not bullet proof, but it's decreased the achyness in my typing fingers!

EDIT - I found a few bugs with the function; namely I could not change dir to a directory that contained spaces. Once I made a change to correct this problem, I could no longer issue 'cd' to return to my home directory.

Here are my change to correct these problems:


function cd {
if [ -z "$2" ]
then
if [ -z "$1" ]
then
builtin cd
else
builtin cd "$*"
fi
else
builtin cd `echo $PWD | sed s/$1/$2/`
fi
}

1 comment:

Unknown said...

I too remember using cd that way about 20 years ago. I guess that capability got lost or was part of a specific shell.