~bin/
things in my bin
Fri Jan 29 08:34:04 2010

Tinkering around with something today, cause I end up in directories like:

/client/company1/archive/in/837

wanting to go to

/client/company2/archive/in/837

I wrote it a few ways - so far I think I like this the best. So yeah, with this function in my .bashrc I can say

s company1 company2

to sed pwd and do that directory hop.

# cd with sed
# example:
# /usr/lib/foo$ s lib src
# /usr/src/foo$
s() {
 local cd="$PWD"
 if [ "$1" = "--complete" ]; then
  awk -v q="${2/s /}" -v p="$PWD" '
   BEGIN {
    split(p,a,"/")
    for( i in a ) if( a[i] && tolower(a[i]) ~ tolower(q) ) print a[i]
   }
  '
 else
  while [ $1 ]; do
   cd="$(echo $cd | sed "s/$1/$2/")"
   shift; shift
  done
  shopt -s cdspell
  cd $cd
  shopt -u cdspell
 fi
}
complete -C 's --complete "$COMP_LINE"' s

It takes pairs of arguments and seds arg to arg+1. The shopt stuff fixes some typos - I dunno why I don't like it enabled all the time - but I feel like it has a bit more panache than just a [ -d "$cd" ] && cd $cd.

(Updated to add tab completion)