Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bash script regex to get directory path up nth levels

Tags:

regex

bash

sed

I'm using PWD to get the present working directory. Is there a SED or regex that I can use to, say, get the full path two parents up?

like image 918
Steve Avatar asked Sep 24 '10 18:09

Steve


2 Answers

Why sed or regex? Why not dirname:

parent=`dirname $PWD`
grandparent=`dirname $parent`

Edit:

@Daentyh points out in the comments that apparently $() is preferred over backquotes `` for command substitution in POSIX-compliant shells. I don't have experience with them. More info:

http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_06_03

So, if this applies to your shell, you can (should?) use:

parent=$(dirname $PWD)
grandparent=$(dirname $parent)
like image 177
Bert F Avatar answered Nov 15 '22 23:11

Bert F


This should work in POSIX shells:

echo ${PWD%/*/*}

which will give you an absolute path rather than a relative one.

Also, see my answer here where I give two functions:

cdn () { pushd .; for ((i=1; i<=$1; i++)); do cd ..; done; pwd; }

which goes up n levels given n as an argument.

And:

cdu () { cd "${PWD%/$1/*}/$1"; }

which goes up to a named subdirectory above the current working directory.

like image 21
Dennis Williamson Avatar answered Nov 15 '22 23:11

Dennis Williamson