Extract the file name, extension and directory in Bash
Split a path into directory, file name and extension with basename, dirname and Bash parameter expansion.
Bash has no built-in function to split a file name, but parameter expansion and basename / dirname cover the usual needs.
Extract the file name and extension
Apply parameter expansion to the base name:
filename=$(basename -- "/path/to/example.lst")
echo ${filename##*.} # extension
echo ${filename%.*} # file name without extension
Directory and base name
VAR=/path/to/mydir/file.c
DIR=$(dirname "${VAR}")
echo "${DIR}" # /path/to/mydir
basename "${VAR}" # file.c
Older approach with cut
FILE=/path/to/example.lst
NAME=`echo "$FILE" | cut -d'.' -f1`
EXTENSION=`echo "$FILE" | cut -d'.' -f2`
Notes
- The
cutapproach splits on every dot. It returns the wrong result for names with several dots (such asarchive.tar.gz) and for paths that contain a dot in a directory name. Parameter expansion on the base name avoids both problems. - The comments of the original snippet were swapped (
##*.returns the extension,%.*returns the name without extension). They are corrected here. - Example paths were made generic.