I want to get the filename (without extension) and the extension separately.
The best solution I found so far is:
NAME=`echo "$FILE" | cut -d'.' -f1` EXTENSION=`echo "$FILE" | cut -d'.' -f2`
This is wrong because it doesn't work if the file name contains multiple .
characters. If, let's say, I have a.b.js
, it will consider a
and b.js
, instead of a.b
and js
.
It can be easily done in Python with
file, ext = os.path.splitext(path)
but I'd prefer not to fire up a Python interpreter just for this, if possible.
Any better ideas?
Sometimes the users need to read the basename of the file only by removing the file extension. Filename and extension can be separated and stored on different variables in Linux by multiple ways. Bash built-in command and shell parameter expansion can be used to remove the extension of the file.
Remove File Extension Using the basename Command in Bash If you know the name of the extension, then you can use the basename command to remove the extension from the filename. The first command-Line argument of the basename command is the variable's name, and the extension name is the second argument.
To find out file types we can use the file command. Using the -s option we can read the block or character special file. Using -F option will use string as separator instead of “:”. We can use the –extension option to print a slash-separated list of valid extensions for the file type found.
First, get file name without the path:
filename=$(basename -- "$fullfile") extension="${filename##*.}" filename="${filename%.*}"
Alternatively, you can focus on the last '/' of the path instead of the '.' which should work even if you have unpredictable file extensions:
filename="${fullfile##*/}"
You may want to check the documentation :
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With