Question

I found the following "trick" to get the file name and its extension.

filename="my file.ext"
name=${filename%.*}
ext=${filename#*.}

Could you explain those ${filename%.*} and ${filename#*.} things and give a link to the relevant documentation ?

Was it helpful?

Solution

${filename%.*}   
# % Deletes shortest match of pattern ".*" from back of "filename".

${filename#*.}   
# Deletes the pattern '*.' from front of filename i.e. removes the name

The Linux Documentation project has this page on Manipulating Strings. Go down to the section marked substring removal

OTHER TIPS

These are both a form of "Remove matching prefix pattern" see bash man page and search for Remove matching prefix pattern.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top