How to extract partial path from pwd to tcsh?

I want to basically implement an alias (using cd) that will take me to the fifth directory in my pwd. that is, If my pwd /hm/foo/bar/dir1/dir2/dir3/dir4/dir5

, I need my alias, say cdf, to take me in /hm/foo/bar/dir1/dir2

. So basically I'm trying to figure out how I split a given path into a specific number of directory levels in tcsh.

Any pointers?

Edit: Ok, I came this far to print the directory I want to use in awk:

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

I find it hard to cd over this as it has already turned into a mess of escaped characters.

+3


source to share


2 answers


@Carpetsmoker's solution using cut

is nice and simple. But since his solution is awkwardly using a different file and source

, here's a demo on how to avoid it. Using single quotes prevents premature evaluation.

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

      




Here's a simple demo of how single quotes can work with reverse windows:

% alias pwd2 'echo `pwd`'
% alias pwd2
echo `pwd`
% pwd2
/home/shx2

      

0


source


This should do the trick:

alias cdf source ~/.tcsh/cdf.tcsh

      

And in ~/.tcsh/cdf.tcsh

:



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

      

We use a tool pwd

to get the current path and pass it to cut

where we split the separator /

( -d/

) and show the first 5 fields ( -f1-6

).
You can see cut

how very lightweight awk

; in many cases this is sufficient and makes things very simple.

The problem with your alias is tcsh quircky's quoting rules. I'm not even going to try to fix it. We use source

to get around it all; tcsh has no functions, but you can emulate them with this. I never said it was beautiful.

+2


source







All Articles