:: home : bio : blog : art
Nights drawing in over the city. Winter 2024 in Edinburgh.
September
Sun Mon Tue Wed Thu Fri Sat
         
24

Contact


 

Archives

Recent Posts

Sun, 24 Sep 2023
WILL: Getting the File Name from a Whole Path
# 20:36 in ./tech

There is a more straightforward way to do this, plus a more arcane way (syntax-wise). There's a lot of arcane in the Bash Shell and in some ways, it's like Vim: you just have to get used to things, try and remember them and not ask "why?" too much.

If you have a file path and want to know the last part (usually the file name) only, you can use the command basename (man basename) e.g. If I have a path : /usr/include/stdio.h, then :

basename /usr/include/stdio.h

Gives me : stdio.h.

The command also has options to strip a suffix (e.g. the ".h" part).

Alternatively, a more arcane was is to use the parameter expansion functionality of the Bash shell.

FILENAME="/usr/include/stdio.h"
echo "${FILENAME##*/}"

This is looking for a pattern ("##") and stripping everything up to the last "/" (*/).

This also gives : stdio.h

Did I mention arcane? There are are lot of very useful features like this in the Bash shell but they can just be a little hard to remember sometimes (and you have to watch out for "gotchas" using them!).

Reference:

See Bash Manual : Parameter Expansion


© Alastair Sherringham 2023
Powered by Blosxom.
Still going after all these years.