How to use regex with find command?

Viewed 561013

I have some images named with generated uuid1 string. For example 81397018-b84a-11e0-9d2a-001b77dc0bed.jpg. I want to find out all these images using "find" command:

find . -regex "[a-f0-9\-]\{36\}\.jpg".

But it doesn't work. Something wrong with the regex? Could someone help me with this?

9 Answers

on Mac OS X (BSD find): Same effect as the accepted answer.

$ find -E . -regex ".*/[a-f0-9\-]{36}.jpg"

man find says -E uses extended regex support

NOTE: the .*/ prefix is needed to match a complete path:

For comparison purposes, here's the GNU/Linux version:

$ find . -regextype sed -regex ".*/[a-f0-9\-]\{36\}\.jpg"

If you want to maintain cross-platform compatibility, I could find no built-in regex search option that works across different versions of find in a consistent way.

Combine with grep

  1. As suggested by @yarian, you could run an over-inclusive find and then run the output through grep:

find . | grep -E '<POSIX regex>'

This is likely to be slow but will give you cross-platform regex search if you need to use a full regular expression and can't reformat your search as a glob

Rewrite as a glob

  1. The -name option is compatible with globs which will provide limited (but cross-platform) pattern matching.

You can use all the patterns that you would on the command line like * ? {} **. Although not as powerful as full regex, you might be able to reformulate your search to globs depending on your use-case.

Internet search for globs - many tutorials detailing full functionality are available online

One thing I don't see covered is how to combine regular expressions with regular find syntax.

Eg: I want to find core dump files on BSD / Linux, I change to the root I want to scan.. eg: cd / then execute:

find \( -path "./dev" -o -path "./sys" -o -path "./proc" \) -prune -o -type f -regextype sed -regex ".*\.core$" -exec du -h {} \; 2> /dev/null

So I am using the prune command to exclude multiple system directories, before doing regular expression on the remaining files. Any error output (stderr) is deleted.

The important part is to use the Find syntax first, then OR (-o) with the regular expression.

Related