3

I want to basically implement an alias (using cd) which takes me to the 5th directory in my pwd. i.e. If my pwd is /hm/foo/bar/dir1/dir2/dir3/dir4/dir5, I want my alias, say cdf to take me to /hm/foo/bar/dir1/dir2 . So basically I am trying to figure how I strip a given path to a given number of levels of directories in tcsh.

Any pointers?

Edit: Okay, I came this far to print out the dir I want to cd into using awk:

alias cdf 'echo `pwd` | awk -F '\''/'\'' '\''BEGIN{OFS="/";} {print $1,$2,$3,$4,$5,$6,$7;}'\'''

I am finding it difficult to do a cd over this as it already turned into a mess of escaped characters.

Martin Tournoij
  • 26,737
  • 24
  • 105
  • 146
Abhinav
  • 33
  • 5

2 Answers2

2

This should do the trick:

alias cdf source ~/.tcsh/cdf.tcsh

And in ~/.tcsh/cdf.tcsh:

cd "`pwd | cut -d/ -f1-6`"

We use the pwd tool to get the current path, and pipe that to cut, where we split by the delimiter / (-d/) and show the first 5 fields (-f1-6).
You can see cut as a very light awk; in many cases it's enough, and hugely simplifies things.

The problem with your alias is tcsh's quircky quoting rules. I'm not even going to try and fix that. We use source to evade all of that; tcsh lacks functions, but you can sort of emulate them with this. Never said it was pretty.

Martin Tournoij
  • 26,737
  • 24
  • 105
  • 146
  • The solution you provided grabs the pwd when the shell starts and behaves like a hard coded path. How do I make the alias evaluate pwd when it is invoked? – Abhinav Jul 01 '15 at 19:39
  • much simpler than using `source`, use `'` instead of `"`. – shx2 Jul 02 '15 at 06:21
  • @shx2 Backticks (\`) don't workinside single-quoted strings(`'`). – Martin Tournoij Jul 02 '15 at 07:32
  • @Carpetsmoker see my answer to understand how to make them work. The use of single quotes defers the evaluation of the backticks until the alias is used, instead of evaluating it at the the time the alias is defined. – shx2 Aug 02 '15 at 20:20
0

@carpetsmoker's solution using cut is nice and simple. But since his solution awkwardly uses another file and source, here's a demonstration of how to avoid that. Using single quotes prevents the premature evaluation.

% alias cdf 'cd "`pwd | cut -d/ -f1-6`"'
% alias cdf
cd "`pwd | cut -d/ -f1-6`"

Here's a simple demonstration of how single quotes can work with backticks:

% alias pwd2 'echo `pwd`'
% alias pwd2
echo `pwd`
% pwd2
/home/shx2
shx2
  • 61,779
  • 13
  • 130
  • 153