Soichiro
Soichiro

Reputation: 91

recursively find and copy specific mimetype files

How do I modify the below command in a way that the search and the copy are performed based on a file's mimetype instead of using an extension such as (mp4, mkv, docx, etc)?

find . -name '*.wmv' -exec cp {} /media/backup/ \;

Upvotes: 0

Views: 389

Answers (3)

Gilles Quénot
Gilles Quénot

Reputation: 185254

Like this, for only video files:

find . -type f -exec bash -c '
    file -i "$1" | grep -q ": video/" && mv "$1" /media/backup/
' -- {} \;

file(1) — determine file type

Upvotes: 2

Soichiro
Soichiro

Reputation: 91

I tried both

find . -type f -exec bash -c '
    file -i "$1" | grep -q "video/" && mv "$1" /media/backup/
' -- {} \;

and

find . -type f -exec sh -c 'file -b --mime-type "$1" | grep -q "video" ' Find {} \; -a -exec mv -t /media/backup {} \;

The first code also moved some audio files whereas, the second one did not. Consequently, the second code works better for me.

Anyway, thank you guys for your help.

Upvotes: 0

GBLightning
GBLightning

Reputation: 29

Could you try that solution?

cp `find . -type f -exec file --mime-type {$1} \; | grep ": video/" | awk -F ":" '{print $1}'` /media/backup/

The cp command has to copy each item from the list (see the expression in the ``) to the folder "/media/backup/".

The find expression in the `` have to return the list of files whose MIME type is "video".

The file --mime-type {$1} expression has to return the MIME data for each file. (Example of output data: "./video.mkv: video/x-matroska")

The grep command is needed to leave only files that have the pattern ": video/". (I hope the target files do not contain that pattern in their paths and names).

The awk expression is needed to get only the path and file name (without MIME data).


Upvotes: 1

Related Questions