Bash: Script for finding files by mime-type

Viewed 6460

First, I am not experienced in scripting, so be gentle with me

Anyway, I tried making a script for finding files by mime-type ( audio, video, text...etc), and here's the poor result I came up with.

#!/bin/bash

FINDPATH="$1"
FILETYPE="$2"


locate $FINDPATH* | while read FILEPROCESS

do

   if  file -bi "$FILEPROCESS" | grep -q "$FILETYPE"
   then
      echo $FILEPROCESS
   fi

done

It works, but as you could guess, the performance is not so good.

So, can you guys help me make it better ? and also, I don't want to rely on files extensions.

Update:

Here's what I am using now

#!/bin/bash

FINDPATH="$1"


find "$FINDPATH" -type f | file -i -F "::" -f - | awk -v FILETYPE="$2"  -F"::" '$2 ~ FILETYPE { print $1 }'
3 Answers
#!/usr/bin/env bash

mimetypes=$(sed -E 's/\/.*//g; /^$/d; /^#/d' /etc/mime.types | uniq)
display_help(){
    echo "Usage: ${0##*/} [mimetype]"
    echo "Available mimetypes:"
    echo "$mimetypes"
    exit 2
}

[[ $# -lt 1 ]] && display_help

ext=$(sed -E "/^${1}/!d; s/^[^ \t]+[ \t]*//g; /^$/d; s/ /\n/g" /etc/mime.types | sed -Ez 's/\n$//; s/\n/\\|/g; s/(.*)/\.*\\.\\(\1\\)\n/')
find "$PWD" -type f -regex "$ext"
Related