Find – Regular Expression in Name

findgnu

suppose I write:

find . -regex "[0-9]{4}-[0-9]{2}-[0-9]{2}-(foo|bar).csv.gz" -printf "%f\n"

This command looks to me like it should work. I have iterated through the various regextype options and various regex formats, but am unable to get this sort of regex to work through find. Is there something simple I am getting wrong here regarding find and the regular expression parser?

Best Answer

Find's -name doesn't take regular expressions (this was used in the original version of the question). It takes shell globs, and that isn't a valid shell glob. You want to use the -regex test, but also need to tell it to use extended regular expressions or any other flavor that understands the {N} and foo|bar notations. Finally, unlike -name, the -regex test looks at the entire pathname, so you need something like this:

$ find . -regextype posix-extended -regex ".*/[0-9]{4}-[0-9]{2}-[0-9]{2}-(foo|bar).csv.gz" -printf "%f\n"
5678-34-56-bar.csv.gz
1234-12-12-foo.csv.gz

If you want to use -name, you could do:

find . \( \
       -name "[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]-foo.csv.gz" \
    -o -name "[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]-bar.csv.gz" \
       \) -printf "%f\n"
Related Question