Find the answer to your Linux question:
Results 1 to 4 of 4
Hello all, First, I am not experienced in scripting, so be gentle with me Anyway, I tried making a script for finding files by type ( audio, video, text...etc), and ...
  1. #1
    Just Joined!
    Join Date
    Jul 2011
    Posts
    2

    Bash script for finding files by type

    Hello all,

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

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

    Code:
    #!/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.

  2. #2
    Linux Guru
    Join Date
    May 2011
    Posts
    1,842
    Why is it poor, as you say? The "file" command you are calling on each file takes some time to run, I'm not sure if you can get around that.

    I would not have used "locate" there, I'd just use "find", but I'm not sure if that is a difference-maker.

  3. #3
    Just Joined!
    Join Date
    Jul 2011
    Posts
    2
    Right now, this is how I am doing it, this way "file" command runs only once.

    Cause someone has pointed me out to the fact that forking "exec" is expensive this one runs faster

    "also I found out that mimetype returns better results than 'file' "

    Code:
    #!/bin/bash
    
    FINDPATH="$1"
    
    
    find "$FINDPATH" -type f | mimetype -i -F "::" -f - | awk -v FILETYPE="$2"  -F"::" '$2 ~ FILETYPE { print $1 }'

  4. #4
    Linux Guru
    Join Date
    May 2011
    Posts
    1,842
    Yes, having the file command not iterate over each found file makes sense, though I didn't think to try it - for some reason, I thought file only ran on one file at a time. I've never used mimetype before, good to know!

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
...