How to extract the last two (or any number) directories from a path with sed?

I'm really looking for a generic solution here, but for the sake of example, let's say I'm looking for the deepest 2 directories in a path. e.g.: Given a path /home/someone/foo/bar, how can I use sed (or awk) to get foo/bar

It would be simple if the first part of the path were always the same, but in my case, I'm looking for an expression that will work for any arbitrary path, and ideally, for any depth n.

If the path has fewer than n (in this case 2) levels, it's not important how the command behaves.

I went do this today and found it tricky. I started to write a loop to do it instead, but I can't shake the feeling that this must be possible in a single command. I could be wrong. Any ideas?


Solution 1:

echo "/your/directory/here/bla" | awk -F"/" '{ print "/"$(NF-1)"/"$NF }'

should work with a find, i didn't try, but something like this should be working :

find /yourfolder/structure -type d | awk -F"/" '{ print "/"$(NF-1)"/"$NF }'

FYI, $NF is the latest field found in awk, $(NF-1), the previous.

Solution 2:

In awk, change your field separator to slash:

$ echo /home/someone/foo/bar | awk -F / -v OFS=/ '{ print $(NF-1), $NF }'
foo/bar

This sets the input field separator and output field separator both to slash and then prints the second-to-last field value, the field separator, and then the last field value.

n-value solution

$ echo /home/someone/foo/bar | awk -F / -v n=3 '
    { o = $NF; for (f=1; f<n; f++) o = $(NF-f) "/" o; print o }
  '
someone/foo/bar

This uses a loop to extract the desired number of directories.