1

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?

peterh
  • 4,953
  • 13
  • 30
  • 44
steve c c
  • 158
  • 5

2 Answers2

3
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.

olivierg
  • 524
  • 2
  • 8
  • 27
1

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.

Adam Katz
  • 951
  • 8
  • 17
  • It's not universal. Because every time you have to calculate value for NF – ALex_hha Oct 20 '17 at 19:45
  • `NF` is built into awk, which calculates it for each given line of input. `NF` is specified by the [POSIX standard for awk](http://pubs.opengroup.org/onlinepubs/9699919799/utilities/awk.html), so it will work in any awk implementation. I'd call that universal. – Adam Katz Oct 20 '17 at 19:46
  • I was talking about your first solution. You have to calculate the shift for different level of depth. Your second solution seems more elegant and universal – ALex_hha Oct 20 '17 at 21:51
  • Ah, I see where you were going with that now. Yes, my first solution works for two fields (for one field, it's just `awk -F/ '{print $NF}'`) but it doesn't scale for n values. That's why there's an n-value solution. – Adam Katz Oct 20 '17 at 21:53