1

I need to find all files in root directory that begin with 3 digits and using the find command, so far I've tried with find . -type f -name '[[digit]]'*' | grep -E '.*/[100-999]+$' but it shows me completely different result. What am I doing wrong? What should I do to get the correct result? Please help

Maciek738
  • 11
  • 1

1 Answers1

2

Note that [100-999] is equal to [0-9], and your regex requires the file name to only contain one or more digits. Also, you missed the colons in the POSIX character class definition, [[digit]] must look like [[:digit:]] if you plan to match a digit in the glob -name pattern.

If you want to find files with name starting with 3 digits (and then there can be anything, including more digits) you can use

find . -type f -name '[[:digit:]][[:digit:]][[:digit:]]*'
find . -type f -name '[0-9][0-9][0-9]*'
find . -type f -regextype posix-extended -regex '.*/[0-9]{3}[^/]*$'

Note:

  • find . -type f -name '[[:digit:]][[:digit:]][[:digit:]]*' or find . -type f -name '[0-9][0-9][0-9]*' - here, the name "pattern" is a glob pattern that matches the entire file name and thus it must start with 3 digits and then * wildcard matches any text till the file name end
  • find . -type f -regextype posix-extended -regex '.*/[0-9]{3}[^/]*$' - if you prefer to play with regex, or extend in the future - it matches any text till last / and then 3 digits and any text other than / till the end of string. If there can be only three and not four digits at the start, you need
find . -type f -regextype posix-extended -regex '.*/[0-9]{3}([^0-9][^/]*)?$'

Here,

  • .*/ - matches up to the last / char including it
  • [0-9]{3} - any three digits
  • ([^0-9][^/]*)? - an optional occurrence of a non-digit and then zero or more chars other than a /
  • $ - end of string.
Wiktor Stribiżew
  • 484,719
  • 26
  • 302
  • 397
  • Curious about `[[:digit:]]`, is there a shell that doesn't support `[0-9]` ? – Sundeep May 25 '21 at 08:54
  • Also, you could simplify `[0-9]{3}([^0-9][^/]*)?$` to `[0-9]{3}[^0-9/]*$` – Sundeep May 25 '21 at 08:55
  • 1
    @Sundeep No, `[0-9]{3}[^0-9/]*$` won't match `123-good-name01.txt` – Wiktor Stribiżew May 25 '21 at 08:56
  • Oh, good point... possessive quantifier would have made that easier.. – Sundeep May 25 '21 at 08:58
  • Good point again, I just tried what I thought would work, but didn't (lookaround helps though).. I think `[^0-9]` should be `[^0-9/]` though, otherwise `./123/-good-name01.txt` will match – Sundeep May 26 '21 at 10:28
  • Just rephrasing the previous comment I deleted: I doubt a possessive quantifier is necessary here. [Here](https://stackoverflow.com/questions/51264400/) is a good use case for a possessive quantifier. – Wiktor Stribiżew May 28 '21 at 09:59