Search code examples
regexbashunixfind

find command with 'regex' match not working


Am trying to do a simple file-name match with this below regex which I tested to be working from this page for a sample file-name ABC_YYYYMMDDHHMMSS.sha1

ABC_20[0-9]{2}(0[1-9]|1[0-2])([0-2][0-9]|3[0-1])([0-2][0-3])([0-5][0-9])([0-5][0-9])\.sha1

When I couple this in the -regex flag of find like

find . -type f -regex "ABC_20[0-9]{2}(0[1-9]|1[0-2])([0-2][0-9]|3[0-1])([0-2][0-3])([0-5][0-9])([0-5][0-9])\.sha1"

the command is not identifying the file present in the path (e.g ABC_20161231225950.sha1). Am aware of many existing regex-types from this page, but I realized my type is posix-extended and tried as below,

find . -type f -regextype posix-extended -regex 'ABC_20[0-9]{2}(0[1-9]|1[0-2])([0-2][0-9]|3[0-1])([0-2][0-3])([0-5][0-9])([0-5][0-9])\.sha1'

and still no result. I searched around some similar questions of this type, but they were involving giving the wrong regex leading to files not being found. In my case, though the regex is found to be proper. I need to know what am I missing here. Also possibly how to debug non matching issues when using -regex in find.

Note:- I could do some optimizations over the capturing groups in the regex, but that is not in the scope of the current question.


Solution

  • add .* at the start of your regex because you will always get something like ./ at start of path

    find . -type f -regextype posix-extended -regex '.*ABC_20[0-9]{2}(0[1-9]|1[0-2])([0-2][0-9]|3[0-1])([0-2][0-3])([0-5][0-9])([0-5][0-9])\.sha1'