Working with unix shell and no way you wont end up extracting file names from paths. Well there is a usual way to do it.
>basename /my/big/long/path/to/a/little/bitty/file file
Here is another way:
f1=/my/big/long/path/to/a/little/bitty/file
f2=./my/big/long/path/to/a/little/bitty/file
f3=my/big/long/path/to/a/little/bitty/file
f4=file
echo ${f1##*/}
echo ${f2##*/}
echo ${f3##*/}
echo ${f4##*/}
# This is how you get value out
filename=${f1##*/}
Output
file file file file
Small Caveat
Above soln. gives slight different result than basename when the path name is a directory that ends in ‘/’. basename /my/big/long/path/to/a/little/bitty/ outputs bitty whereas above outputs nothing.
>basename /my/big/long/path/to/a/little/bitty/
bitty
>f1=/my/big/long/path/to/a/little/bitty/
>echo ${f1##*/}
>
But then, if you are trying to extract file name then /my/big/long/path/to/a/little/bitty/ should return nothing as there is no filename in the path. So logically my solution is correct.
You can use basename but that will be slow as it will launch a new child process. I can have some performance comparison but I ll leave that for later….when I get a chance. But its no-brainer that you ll get great boost in performance if you are extracting file name in a tight loop.
Leave a Reply to Jacquelyn Cancel reply