List files whose names consist of two digits

Viewed 363

I'm trying to find all file or directory that only contain two digits in the current directory.

The regex for exactly two digits is

/^\d{2}$/

So I tried the following but because of the backslash and forwardslash I got stuck

find path ".//^\d{9}$/"

I use "./[regex]" because I am looking file or directory that is in the current directory

3 Answers

You don't need find here. The command below will list files and directories whose name consists of two digits in the current directory.

printf '%s\n' ./[0-9][0-9]
# drop `./' if you don't need it

If you have to use a regex for some reason, here is how it's done with GNU find and BSD find respectively:

find . -maxdepth 1 -regextype egrep -regex '\./[0-9]{2}'
find -E . -maxdepth 1 -regex '\./[0-9]{2}'

And with any POSIX-compliant find, this will do the same thing:

find . ! -name . -prune ! -name '*[!0-9]*' -name '??'
# number of question marks determines the length of filename

Some may argue that [0-9] may match more than digits from 0 through 9; if that's a concern, set LC_ALL to C first.

Use find like so:

find . -name '*[0-9]*[0-9]*'
 find . -regextype posix-extended -regex "^.*[[:digit:]]{2}.*$"

Specify regular expression type with the regextype flag as well as regular expression to search for with -regex. Search for all entries that have 2 digits any where in the directory/filename.

Related