28

I have been trying to create a find command string that will find all files that end with a number 1-99 but exclude all others.

e.g. I want to find myfile1 myfile99 but not myfile456 and not myfilebackup

The regex I'm thinking of is myfile[1-9]{1,2} but I can't get this to work with find.

find . -regex '.*myfile[0-9]{1,2}' OR find . -iname 'myfile[0-9]{1,2}'

From what I can see it's the {1,2} part that is not working.

(by the way can you use -name -regex interchangably?)

Any help appreciated.

1
  • 1
    -iname (and -name) use globs, which do not have this syntax.
    – l0b0
    Mar 7, 2013 at 13:51

2 Answers 2

23

You could try

find . -regex '.*myfile[0-9][0-9]?'

or

find . \( -name "myfile[0-9][0-9]" -o -name "myfile[0-9]" \)
1
  • Thanks - the first line is working for me. I had tried this with -iname but I don't think it supports the syntax or else I'm doing something wrong.
    – Lukas88
    Mar 7, 2013 at 14:16
23

If you have GNU find, you can use another regular expression type:

find . -regextype sed -regex '.*myfile[0-9]\{1,2\}'

According to GNU find uses a neutered Emacs regular expression syntax by default - Emacs supports \{from,to\} syntax, but at least GNU find doesn't support it.

Strangely, the reference manual doesn't include a section on the sed regular expression syntax, so who knows which parts of it are supported.

2
  • 2
    sed like ed seems to be an alias for posix-basic, so should be compatible with POSIX BRE (though supports some extensions like \+). It's not compatible with GNU sed where for instance [\n] matches a newline instead of the backslash or n required by POSIX. See also -regextype posix-extended for POSIX EREs (so .*myfile[0-9]{1,2}), also with extensions like \s or \< Aug 7, 2017 at 10:48
  • I never knew about -regextype. It seems that if you use -regextype egrep it seems like you can avoid the backslashes. Dec 3, 2019 at 7:10

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .