Extract filename and extension in Bash Extract filename and extension in Bash bash bash

Extract filename and extension in Bash


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 :


~% FILE="example.tar.gz"~% echo "${FILE%%.*}"example~% echo "${FILE%.*}"example.tar~% echo "${FILE#*.}"tar.gz~% echo "${FILE##*.}"gz

For more details, see shell parameter expansion in the Bash manual.


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