Get standard / preferred file extension

I can determine file types using file . Can I get the default extension (preferred) for a 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 will be .gif and .txt

I know that extensions do not matter for UNIX, but for me this is important.

+6
source share
2 answers

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

What you can do is get the mime type first:

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

Then use this awk to get the file extension:

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

OUTPUT:

 jpeg 
+2
source

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

 case $(file - <"$file") in '-: GIF image'* ) ext=gif ;; '-: ASCII text'* ) ext=txt ;; # etc esac 
0
source

Source: https://habr.com/ru/post/945442/


All Articles