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/\\/[^\\/]*$//

+3


source to share


3 answers


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

+3


source


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 /

.

+1


source


Same idea as @josifoski

pwd | sed ':a;\#/\(.*\)/[^/]*# {p;s##/\1#;ba}'

      

Print and loop until there is only one folder name, deleting each loop of the last folder path

+1


source







All Articles