Page 1 of 1
Forum

Welcome to the Tweaking4All community forums!
When participating, please keep the Forum Rules in mind!

Topics for particular software or systems: Start your topic link with the name of the application or system.
For example “MacOS X – Your question“, or “MS Word – Your Tip or Trick“.

Please note that switching to another language when reading a post will not bring you to the same post, in Dutch, as there is no translation for that post!



Linux/macOS - Just ...
 
Share:
Notifications
Clear all

[Solved] Linux/macOS - Just get a filename, or filename parts, in a script

1 Posts
1 Users
0 Reactions
659 Views
 Hans
(@hans)
Famed Member Admin
Joined: 11 years ago
Posts: 2805
Topic starter  

Sometimes we need to get part of the full path of a filename.

I'll use this full path in the examples:

/path/to/you/filename.ext

Say you want only the filename with extension, then you can use "basename":

basename /path/to/you/filename.ext

This results in

filename.ext

Now we can use this is scripts, like so:

~ $ echo $(basename /path/to/you/filename.ext)       

filename.ext
~ $ myfile=/path/to/you/filename.ext                    
~ $ echo $(basename $myfile)            

filename.ext

 

When using variables, you can do some neat tricks as well, if you want just the extension, or just the filename without extension, or a "double" extension (targ.gz for example):

~ $ myfile="example.tar.gz"

~ $ echo "${myfile%%.*}"
example

~ $ echo "${myfile%.*}"
example.tar

~ $ echo "${myfile#*.}"
tar.gz

~ $ echo "${myfile##*.}"
gz

Anyhoo ... hope this is useful to anyone - keeping it here for my own reference as well 😁 


   
ReplyQuote
Share: