GNU find does not include any regex operators that only apply to the basename. This is unfortunate. The closest we can come is by modifying the regex to strip slash-delimited portions from the front of the regex:
find /my/path -regextype posix-extended -regex ".*/reg1"
This will work for normal linux path names, but could fail for pathnames with unusual characters (newlines, for example).
As geekosaur points out, your input regular expressions should not match multiple components. If you don't have any control over the regex (say, if it's passed as a variable $REG1), you can try mangling it to convert .
into [^/]
:
find /my/path -regextype posix-extended -regex ".*/${REG1/./[^/]}"
This is going to fail for a lot of regular expressions (for instance, '.*.txt' gets horribly mangled). However, if you know that the regex are going to be simple then it might work.
For a slower but working solution, you can do all the pattern matching inside an -exec
block:
find /my/path -exec bash -c 'basename "$0" | egrep -q '"'$REG1'"' && echo "$0"' '{}' ';'
The logic here is that find
enumerates over all files and assigns them to $0
in the subshell. The subshell uses basename
and egrep
to filter the output down to paths that match the input regex. Note that egrep finds local matches; if you want to match the full basename, use egrep -q '"'^$REG1\$'"'
Depending on the semantics of the input regular expression (e.g. if $REG1
is intended to match any substring of the basename), you can get better performance for first searching for the regex in the whole path and then filtering to just the basename:
find /my/path -regextype posix-extended -regex ".*${REG1}.*" \
-exec bash -c 'basename "$0" | egrep -q '"'$REG1'"' && echo "$0"' '{}' ';'