Search code examples
regexfindposix

find -regex not recognizing what seems like a good query


Using egrep, the regular expression "^.{8}$" matches any filename of exactly 8 characters:

jeff@jbb-lenovo:~/smsn+/kb/vcs/private$ ls | egrep "^.{8}$"
ac7t6-Xo
aQsqsC4-
a_wzemGk
jeff@jbb-lenovo:~/smsn+/kb/vcs/private$ 

But using find, whether I use posix-extended or the ordinary kind, that pattern does not work:

jeff@jbb-lenovo:~/smsn+/kb/vcs/private$ find . -regex "^.{8}$"
jeff@jbb-lenovo:~/smsn+/kb/vcs/private$ find . -regextype posix-extended -regex "^.{8}$"
jeff@jbb-lenovo:~/smsn+/kb/vcs/private$ 

In fact I tried all the other regextypes -- emacs, posix-basic, posix-awk, posix-egrep -- as listed here.


Solution

  • It is not working because output of find will also include ./ before each filename since your path argument is .

    You can use:

    find . -regextype posix-extended -regex "^[^/]{10}$"
    

    Or else:

    find . -regextype posix-extended -regex "^\./[^/]{8}$"
    

    use of [^/] instead of . ensures we don't match filenames in subdirectories.

    Or we could use -maxdepth 1 as well to avoid matched in subdirectories:

    find . -maxdepth 1 -regextype posix-extended -regex "^\./.{8}"