1

I am trying to find all files in the directories and sub-directories on Desktop with a file name starting with prac_ followed by two digits and ending in .c or .o

find ./Desktop -type f -name "prac_[0-9][0-9]*" \( -name "*.c" -o -name "*.o" \)

The problem I'm having is that the above command will bring up files like prac_99BLAHBLAH.o when I only want files with the format prac_99.c.

1
  • 1
    How about -name 'prac_[0-9][0-9].c' -o -name 'prac_[0-9][0-9].o' Jun 17, 2020 at 5:34

2 Answers 2

4

Using * in a filename globbing pattern matches any string whatsoever, so it's correct that the name prac_99BLAHBLAH.o matches the pattern prac_[0-9][0-9]*, and one of *.c or *.o.

Instead, use

find ./Desktop -type f -name 'prac_[0-9][0-9].[co]'

The filename globbing pattern [co] matches the single character c or o, so putting it at the end of the pattern used with -name enables you to find filenames that has either character at the end of the name.

6
1

You're just not restricting the characters between the numbers and file extensions. It can all be a single regex:

find ./Desktop -type f -regex ".*/prac_[0-9][0-9][.][co]"
  • The .*/ at the beginning is because -regex matches on filepaths rather than just filenames.
  • The [.] is a single-character set that matches a period. It's used because a plain . matches any character. Escaping it like \. works too, but I tend to avoid that style because the syntax varies across programming languages (e.g., with an extra escape like \\. or in a raw string like r"\.").
3
  • Is there a particular reason to place the period in [ ]?
    – AdminBee
    Jun 17, 2020 at 9:33
  • 1
    @AdminBee The period will match any character unless it is escaped like "\." or is a single-character set like "[.]". I prefer the latter because I jump between a lot of domain-specific config languages and tend to forget when "\." actually needs to be written as "\\." (or r"\." or with backticks, etc).
    – grencez
    Jun 17, 2020 at 10:17
  • 1
    I would recommend placing it in the answer, it is among others these little hints that make the site so useful ...
    – AdminBee
    Jun 17, 2020 at 10:35

You must log in to answer this question.