Extracting Directory From Path

Hi guys. I'm doing some bash scripting and have run into a snag.

Say I have the path:
/home/one/two/three/

All I need is the 'three' while making a filename.
Is there an easy way to do this? I've tried using grep (because I'm that smart.) cut (as I'm unable to tell how many fields there will be in a path, that doesn't work) and than I gave up and started scouring the internet but can't find anyone trying to do the same thing. Any help would be appreciated.

$ echo "/home/one/two/three/" | ruby -e 'puts gets.gsub(/\/$/,"").split("/")[-1]'
three

$ echo "/home/one/two/three/" | ruby -e 'puts gets.split("/")[-2]'
three

1 Like

You may stick to grep and cut:

echo "/home/one/two/three/" | grep -Eo '[^/]+/?$' | cut -d / -f1

Or just perl:

echo "/home/one/two/three/" | perl -pe 's|^.+?([^/]+)/?$|$1|'
1 Like

Thanks a lot both of you :slight_smile: Got it now.