Strip extension from filename in bash/zsh


You have a filename in the Linux shell and want to strip/remove the filename extension from it - e.g. if you have, you want to get only myarchive as output.


Let’s assume your original filename is saved in the bash variable $filename. Then you can use the following command:

echo $filename | rev | cut -d. -f2- | rev

Why this works:

We need to use this combination of cut and rev because cut doesn’t support something like “Remove only the last field” unless you know the number of fields (which you generally don’t unless you don’t want to support filenames like ).

rev Reverses the filename - e.g. if $filename is, rev $filename _yields _piz.evihcraym cut -d. -f2 Removes only the first field from the input string, delimited by “.” - because the string is reversed, this is equivalent to removing only the last field from the original input

After the we need to _rev_erse the output of cut again to get the desired result