Wiki‎ > ‎

Basename

posted Jul 22, 2016, 8:23 PM by Dong Xu

${variable%pattern} Trim the shortest match from the end ${variable##pattern} Trim the longest match from the beginning ${variable%%pattern} Trim the longest match from the end ${variable#pattern} Trim the shortest match from the beginning

Using Bash, there’s also ${file%.*} to get the filename without the extension and ${file##*.} to get the extension alone. That is,

file="thisfile.txt"
echo "filename: ${file%.*}"
echo "extension: ${file##*.}"


bash-3.2$ FILENAME=somefile.tar.gz bash-3.2$ echo ${FILENAME%%.*} somefile bash-3.2$ echo ${FILENAME%.*} somefile.tar

extension="${filename##*.}" filename="${filename%.*}"

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