David,
Try this:
#!/bin/bash
path="/Users/drew/this/is/a/test/"
lastDir=echo $path | grep -Eo '[^/]+/?$' | cut -d / -f1
echo $lastDir
Regards,
Drew McMillen, Desktop Engineering Team Lead
NIEHS Tech Services Team
(w) 919/313-7683
(m) 919/257-8333
mcmillen at niehs.nih.gov
https://apps.niehs.nih.gov/itsupport/web
David,
You have two different examples
/User/user
and
/User/user/
For the former,
echo ${FILE##*/}
will provide the last item after the last slash, so
bash-3.2$ FILE="/I/want/the/last/directory"; echo ${FILE##*/}
directory
whilst
bash-3.2$ FILE="/I/want/the/last/directory/"; echo ${FILE##*/}
will return nothing as there is nothing after the last slash.
Same problem if you use awk
bash-3.2$ echo "/I/want/the/last/directory" | awk -F "/" '{print $NF}'
directory
bash-3.2$ echo "/I/want/the/last/directory/" | awk -F "/" '{print $NF}'
bash-3.2$
You could then get into 'if' statements and removing characters, etc. However, if all of your users are in /Users, then you could just cheat and do
echo /Users/david/ | cut -d "/" -f 3
Then it wont matter.
Sean
Hi David,
If you only want the last bit of a path, you can also pass the directory variable through the basename command, which will extract the last item, with or without the end /.
e.g.
bash-3.2$ basename /path/to/directory
directory
bash-3.2$ basename /path/to/directory/
directory
Regards,
Daniel Sung
Junior Systems Administrator
Framestore
19-23 Wells Street, London W1T 3PQ
www.framestore.com
Thanks Daniel, Sean and Drew McMillen (offlist)
I now have a working solution thanks to Drew.
Both Daniels and Seans solutions worked perfectly as expected until I attempted to go live. The problem I had:
When I drag a folder into Platypus Droppable it makes the variable as:
/Volumes/Macintosh HD/Users/test
Using basename and Sean's echo both faulted as Platypus doesn't escape the space in Macintosh HD. I tried to see if I could modify Platypus so it provided a complete folder path (/Volumes/Macintosh HD/Users/test) but unfortunately couldn't find a solution.
Drew's provided solution proved successful!
path="/Users/drew/this/is/a/test/"
lastDir=echo $path | grep -Eo '[^/]+/?$' | cut -d / -f1
echo $lastDir
In testing this is working as expected – I have deployed it now successfully.
Thanks to the input of all – Greatly appreciated!
Thanks, David
David,
You just need to learn how to pass/escape spaces.
mac118:~ macsupport$ echo "/Users hello/david/" | cut -d "/" -f 3
david
mac118:~ macsupport$ basename "/Users hello/david"
david
mac118:~ macsupport$ basename /Users hello/david
david
Once you have a string returned, you either will need to quote it or replace the space with an escaped space,
mac118:~ macsupport$ echo "/Users hello/david/" | sed 's/ /\\ /g'
/Users hello/david/
Sean