29

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. Commented Mar 7, 2013 at 13:51

2 Answers 2

24

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.

3
  • 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 \< Commented 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. Commented Dec 3, 2019 at 7:10
  • Sadly, this point about lacking quantifiers (and possibly other features of the full Emacs regex syntax) is not explicitly mentioned in the documentation, with zero clues whatsoever in the man page. Commented Dec 19, 2023 at 1:28
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. Commented Mar 7, 2013 at 14:16

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.