This question already has an answer here:
- Extract filename and extension in Bash 36 answers
How would I get just the filename without the extension and no path?
The following gives me no extension, but I still have the path attached:
source_file_filename_no_ext=${source_file%.*}
Most UNIX-like operating systems have a
basename
executable for a very similar purpose (anddirname
for the path):That unfortunately just gives you the file name, including the extension, so you'd need to find a way to strip that off as well.
So, given you have to do that anyway, you may as well find a method that can strip off the path and the extension.
One way to do that (and this is a
bash
-only solution, needing no other executables):That little snippet sets
xpath
(the file path),xpref
(the file prefix, what you were specifically asking for) andxfext
(the file extension).basename
anddirname
solutions are more convenient. Those are alternative commands:This returns
test.old.img
likebasename
.This is salt filename without extension:
It returns
test.old
.And following statement gives the full path like
dirname
command.It returns
/opt/datastores/sda2
Here is an easy way to get the file name from a path:
To remove the extension you can use, assuming the file name has only ONE dot (the extension dot):
Some more alternative options because regexes (regi ?) are awesome!
Here is a Simple regex to do the job:
Example (grep):
Example (awk):
If you need a more complicated regex: For example your path is wrapped in a string.
Total solution with Regexes:
This function can give you the filename with or without extension of a linux filepath even if the filename has multiple "."s in it. It can also handle spaces in the filepath and if the file path is embedded or wrapped in a string.
If you have to mess with a windows path you can start with this one: