Search code examples
regexlinuxfinddigits

use find to match filenames starting with number


I am trying to find files that have only numbers in their filenames. For example, if I have the files 123.txt, 45.doc, alpha_123, beta_123.txt, 45 and 123, I only want to match files 45 and 123. I have tried various options with find and grep or combinations of them, but nothing worked as I wanted or gave me syntax errors.

Also is there any chance that I can only match for empty files? I tried using the option "empty" but also was unsuccessful, although this was probably due to using the wrong syntax.

This find . -name "[0-9]*" kind of worked, as in it found files with numbers in their filenames, for example file 123 and file 45, but it also found files with an extension, for example 123.txt and 45.doc, and unfortunately this is not what I want.

From the suggestions below (as my original question was heavily edited after answers were posted), what worked exactly as I wanted was $ find . -type f -name '[[:digit:]]*' | grep -E '.*/[0-9]+$'.

I apologise for the initial misleading/ambiguous post, I hope the edited version will prove helpful for other users also confused about how to use find with regex.


Solution

  • Either this:

    $ find -E .  -type f -regex '.*/[[:digit:]]+$'
    

    Or this:

    $ find .  -type f -name '[[:digit:]]*' | grep -E '.*/[0-9]+$'
    

    work to find files with names composed entirely of digits (i.e., no extension)