rokoder

Faster way to extract file name

by on Dec.29, 2011, under Programming

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.

:, , , , , ,

1 Comment for this entry

  • Jacquelyn

    I am so happy to read this. This is the type of manual that needs to be given and not the random misinformation that’s at the other blogs. Appreciate your sharing this best doc.

Leave a Reply

Looking for something?

Use the form below to search the site:

Still not finding what you're looking for? Drop a comment on a post or contact us so we can take care of it!

Blogroll

A few highly recommended websites...

Archives

All entries, chronologically...