Path of current, parent and root directory
I need to print the path to the current parent and root directory in UNIX. I can use commands or shell script. I was able to do this for the current and parent directory, but I don't know how to print it out for the root directory.
Here's what I did:
- current:
pwd
- parent:
echo $(pwd) | sed -e s/\\/[^\\/]*$//
source to share
gnu sed
echo $(pwd) | sed -r -e 'p; :a; s#(.*)/.*#\1#; H; ta; x' | sed '/^$/d'
this will print all directories from current -> root
it uses greedy search for '/', keeping only the left side, adding to the hold area, ta is a conditional branch to substitute, so if there is one, it branches: a, at the end of the x, moves the hold space to the drawing space.
The last sed command is for clearing blank lines
source to share
It seems to me that this is easier to do with awk:
echo $(pwd) | awk 'BEGIN {FS=OFS="/"} {l=NF; while (i++<l-1) {print; NF--}}'
Explanation
This will print all directories from the current -> root. It does this by printing a line, then decrementing the number NF
, the number of fields. Note that I have set the input and output field separators to /
.
source to share