Search for files within a directory

directoryfindosx

I'm trying to search for all files given a certain string / regex value. So if I were to say search for all files that have "hello" in the name, how would I go about doing this? Ever more complex, how would I go about finding a file whose name begins with any two letters followed by a dash and then a number?

I've tried the find command and that has helped in the situation of hello. I would just type find <dir> *hello* but this doesn't work with the regex values.

If I type find -E <dir> -regex '^[a-z]{2}-[1-9]' nothing happens. Even if I type find -E <dir> -regex '*[0-9]*', nothing happens.

Could someone help me with this? Thanks in advance

Best Answer

-regex matches on the whole file path (not just the name), and is anchored by default (^ and $ implicit).

Here, you don't need regexps though, you can use the standard -name which takes a wildcard pattern and matches on the file name, not path:

find . -name '*hello*' -name '[[:alpha:]][[:alpha:]]-[1-9]*'

For file names that start with 2 letters, a hyphen and a digit from 1 to 9 and contain "hello".

With regexps, and here with FreeBSD/OS/X find, that would have to be:

find -E . -regex '.*hello[^/]*' -regex '.*/[[:alpha:]]{2}-[1-9][^/]*'

You need [^/]* instead of .* as otherwise, that would match on ./aa-9/hello/foo/bar for instance.

In any case, find <dir> *hello* doesn't do what you think it does. The shell expands that *hello* glob to the list of non-hidden files or directories in the current directory whose name contains "hello" and passes the result as extra arguments to find.

Related Question