Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get default / preferred file extension

Tags:

unix

I can identify file types with file command. Can I get what is default (preferred) extension for the file?

For example for

tmp_206.file: GIF image data, version 89a, 17 x 17
tmp_202.file: ASCII text, with very long lines, with no line terminators

it would be .gif and .txt

I know extensions do not matter for UNIX, but they do matter for me

like image 699
Jakub M. Avatar asked May 20 '13 17:05

Jakub M.


2 Answers

Some file types support more than 1 extension like jpe, jpeg, jpg etc for jpeg files.

What you can do is to get mime type first using:

mimleType=$(awk -F';' 'NF>1{print $1}' < <(file -bi logo.jpeg))

Then use this awk to get file extension:

awk -v mt=$mimeType '$1==mt{print $2}' /Applications/MAMP/conf/apache/mime.types

OUTPUT:

jpeg
like image 124
anubhava Avatar answered Sep 20 '22 07:09

anubhava


If you have a reasonably limited set of extensions, creating a mapping from file output to your preferred extension is not hard.

case $(file - <"$file") in
  '-: GIF image'* ) ext=gif ;;
  '-: ASCII text'* ) ext=txt ;;
  # etc
esac
like image 23
tripleee Avatar answered Sep 24 '22 07:09

tripleee