Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash: Script for finding files by mime-type

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 }'
like image 660
masamunedark Avatar asked Jul 23 '11 19:07

masamunedark


2 Answers

Forking (exec) is expensive. This runs the file command only once, so it is fast:

find . -print | file -if - | grep "what you want" | awk -F: '{print $1}'

or

locate what.want | file -if -

check man file

-i    #print mime types
-f -  #read filenames from the stdin
like image 199
jm666 Avatar answered Nov 20 '22 16:11

jm666


#!/bin/bash
find $1 | file -if- | grep $2 | awk -F: '{print $1}'
like image 23
Eric Fortis Avatar answered Nov 20 '22 16:11

Eric Fortis