LLI Wiki — My Digital Knowledge Base

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

Mastodon LLIMastodon SocialFosstodon