2
Mar

Extract Extension Name from Filename in Bash Shell

The following commands will extract the file extension string from a given filename. The only trick to these commands is they will give you the final extension after the last ‘.’. In other words, they will not work for extensionless files and files with two dot extension names (like file.tar.gz or similar).

for i in *; do echo $i | sed -e 's/.*[.]\(.*\)/\1/'; done
for i in *; do echo $i | awk -F. '{ print $NF }'; done

This command will grab the first dot extension even if there are two (it will return tar for file.tar.gz).

for i in *; do echo $i | cut -d'.' -f2; done

I’d love to hear your suggestions in the comments if you have a better, more optimized way of doing this.

Feel free to donate if this post prevented any headaches! Another way to show your appreciation is to take a gander at these relative ads that you may be interested in:


There's 4 Comments So Far

Share your thoughts, leave a comment!