Find Command Issues – Directory Not Found with -name or -regex

findpattern matching

I have a directory ~/Documents/machine_learning_coursera/.

The command

find . -type d -name '^machine'

does not find anything

I also tried

find . -type d -regextype posix-extended -regex '^machine'

so as to match the the beginning of the string and nothing.

I tried also with -name:

find . -type d -regextype posix-extended -regex -name '^machine'

and got the error:

find: paths must precede expression: `^machine'

What am I doing wrong here?

Best Answer

find's -name takes a shell/glob/fnmatch() wildcard pattern, not a regular expression.

GNU find's -regex non-standard extension does take a regexp (old style emacs type by default), but that's applied on the full path (like the standard -path which also takes wildcards), not just the file name (and are anchored implicitly)

So to find files of type directory whose name starts with machine, you'd need:

find . -name 'machine*' -type d

Or:

find . -regextype posix-extended -regex '.*/machine[^/]*' -type d

(for that particular regexp, you don't need -regextype posix-extended as the default regexp engine will work as well)

Note that for the first one to match the name of the file also needs to be valid text in the locale, while for the second one, it's the full path that needs to be valid text.

Related Question