Removing a known extension from a filename

If you have a filename or list of filenames, you may want to strip the extension. There are a few ways of “detecting” which part of the filename is the extension, but may not work if your file has multiple extensions (e.g. .tar.gz), contains spaces or periods, or meets other weird criteria. If you know what the extension is, or at least how long it is, you can just pull those characters off the end. This can be done with the ${<varname>::0-<n>} syntax, which will strip <n> characters off the end.

For example, the following code:

fname=/path/to/myfile.txt
echo ${fname::0-4}

will print

/path/to/myfile

Leave a Reply

Your email address will not be published.