The file command is good at determining file types for my needs. Is there any way to map those results to conventional filename extensions?


The file extensions registered on your system should be in /etc/mime.types. So, assuming you managed to extract the file type from the output of file into a variable called type, you can simply:

grep -i "$type" /etc/mime.types | awk '{$1="";print $0}'

or (as suggested by 200_success in the comments), you can use awk alone:

awk -v IGNORECASE=1 '/ENVIRON["type"]/{$1="";print $0}'


$ type=Perl
$ grep -i "$type" /etc/mime.types | awk '{$1="";print $0}'
 pl pm
| improve this answer | |
  • grep | awk can usually be done using awk alone. – 200_success Nov 26 '13 at 17:33
  • @200_success Please see the edited answer. – Joseph R. Nov 26 '13 at 17:36
  • @200_success yes but that is not always a good idea since grep will tend to be faster than an awk that has to check a regex for each line. – terdon Nov 27 '13 at 0:40

This is the same basic idea as @hildred's answer but using a simpler approach (gawk) and modified to deal with file names containing spaces and unknown file types.

Add these lines to your shell's initialization file (~/.bashrc for example, if you are running bash):

 for f in "$@"; do 
  type='unknown extension';
  foo=$(grep -w "$(file --mime-type "$f" | awk '{print $NF}')" /etc/mime.types | 
  awk -F"\t" 'NF>1{print $NF}')
  [ -n "$foo" ] && type="$foo";
  printf "%s\t%s\n" "$f" "$type";

You can now run it like this:

$ get_ext *
cp  unknown extension
file with spaces .jpg   jpeg jpg jpe
foo.pl  pl pm
foo.png png
foo.py  py
foo.txt asc txt text pot brf srt

It will return 'unknown extension' for files that have no associated extension in /etc/mime.types such as cp which is an executable.

| improve this answer | |

proof of concept, does not handle funny characters, assumes first extension is right.

file --mime-type -N *|sed \
   -e 's!^\(.*: \)\(.*\)$!echo \1;grep -e \2 /etc/mime.types!e' \
   -e 's!\n.*/[^     ]\+[    ]\+\([^ ]\+\).*! \1!' \
   -e 's!\n\(.*/[^     ]\)\+!\1!'
| improve this answer | |
  • also assumes gnu sed – hildred Nov 26 '13 at 16:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.