2
Mar
Posted by Derek@TheDailyLinux in Scripting » 4 Comments »
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:
Here are some similar posts that you may be interested in:
There's 4 Comments So Far
March 2nd, 2012 at 10:14 am
How about:
for i in *; do echo ${i##*.}; done
see here for how this works: http://tldp.org/LDP/abs/html/string-manipulation.html
March 2nd, 2012 at 10:51 am
Thanks for that! Always good to know there’s more than one way to skin a cat!
March 4th, 2012 at 10:14 pm
This came via email from a subscriber, Jim. Thanks Jim!
April 21st, 2012 at 12:16 am
I think, Jim, if the goal is to extract only the extension, the correct would be sed -e ‘s/\..*//’, or substitute everything after a dot (scaped) with nothing, isn’t it?
Share your thoughts, leave a comment!