What’s the Best Way to Build a Conditional Find Command for Different File Types?

0
14
Asked By CuriousCoder42 On

I'm working on a project where I need to search through a specific directory to find all types of image files. Currently, I have this command: `find . -type f ( -iname "*.jpg" -o -iname "*.png" -o -iname "*.mp4" ) -print`. However, I anticipate needing to add more file types in the future. I'm wondering if there's a cleaner way to manage this. For instance, could I define a list of file types and incorporate that into the find command? Something like this:

filetypes = [jpg, png, mp4, ... ]
find . -type f -print

4 Answers

Answered By ImageFinderX On

Another straightforward method is to use the `file` command combined with `grep` to find images:

find . | xargs file | grep "image data" | cut -d: -f1

It pulls the image files based on the file type.

DataSeeker99 -

You might want to try using single quotes around 'image data' to ensure accuracy!

Answered By BashMaster5000 On

You can create a loop in bash to handle this more dynamically. Here's a neat example:

(e='jpg png mp4 jpeg gif bmp xwd tiff'; for e in $e; do if [ "$#" -eq 0 ]; then set -- ( -iname "*.$e"; else set "$@" -o -iname "*.$e"; fi; done; [ "$#" -eq 0 ] || set -- "$@" ); unset e; find . -type f "$@" -print)

This is a clever way to utilize bash positional parameters!

Bashlover88 -

This is awesome! Such a brilliant way to use bash.

Answered By FinderGeek77 On

Most versions of the `find` command now support regex. You can shorten your command to:

find . -type f -regex '.*.(jpg|png|mp4)$'

It might look complex, but it reduces the amount of `-iname` arguments you need to use.

FileHunterX -

If you're not too concerned about real-time accuracy, you can use this alternative with `locate`:

locate --regexp "${PWD}.*.(jpg|png|mp4)$"

Answered By TechWizard89 On

In my opinion, using the built-in `-o` operator is the simplest and most readable approach. You could also utilize `-regex` for matching, but as your list grows, managing escaped characters can get tricky. Alternatively, you could store your file patterns in a text file and use `xargs` to read from it like this:

xargs -a patterns.txt -I% find files/ -iname %

If you have a large number of files, consider using the `file` command on all files and then piping that into `grep` to filter for "image". It all depends on your situation though!

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.