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\'.\'
Smallest and simplest solution (in single line) is:
$ file=/blaabla/bla/blah/foo.txt
echo $(basename ${file%.*}) # foo
Usually you already know the extension, so you might wish to use:
basename filename .extension
for example:
basename /path/to/dir/filename.txt .txt
and we get
filename
From the answers above, the shortest oneliner to mimic Python's
file, ext = os.path.splitext(path)
presuming your file really does have an extension, is
EXT="${PATH##*.}"; FILE=$(basename "$PATH" .$EXT)
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 :
I think that if you just need the name of the file, you can try this:
FULLPATH=/usr/share/X11/xorg.conf.d/50-synaptics.conf
# Remove all the prefix until the "/" character
FILENAME=${FULLPATH##*/}
# Remove all the prefix until the "." character
FILEEXTENSION=${FILENAME##*.}
# Remove a suffix, in our case, the filename. This will return the name of the directory that contains this file.
BASEDIRECTORY=${FULLPATH%$FILENAME}
echo "path = $FULLPATH"
echo "file name = $FILENAME"
echo "file extension = $FILEEXTENSION"
echo "base directory = $BASEDIRECTORY"
And that is all =D.
How to extract the filename and extension in fish:
function split-filename-extension --description "Prints the filename and extension"
for file in $argv
if test -f $file
set --local extension (echo $file | awk -F. '{print $NF}')
set --local filename (basename $file .$extension)
echo "$filename $extension"
else
echo "$file is not a valid file"
end
end
end
Caveats: Splits on the last dot, which works well for filenames with dots in them, but not well for extensions with dots in them. See example below.
Usage:
$ split-filename-extension foo-0.4.2.zip bar.tar.gz
foo-0.4.2 zip # Looks good!
bar.tar gz # Careful, you probably want .tar.gz as the extension.
There's probably better ways to do this. Feel free to edit my answer to improve it.
If there's a limited set of extensions you'll be dealing with and you know all of them, try this:
switch $file
case *.tar
echo (basename $file .tar) tar
case *.tar.bz2
echo (basename $file .tar.bz2) tar.bz2
case *.tar.gz
echo (basename $file .tar.gz) tar.gz
# and so on
end
This does not have the caveat as the first example, but you do have to handle every case so it could be more tedious depending on how many extensions you can expect.