Ido Tamir
Ido Tamir

Reputation: 3147

bash find: path changes results with regex exclusion

I want to exclude files from being reported by find using a regex. This however only seems to work if the path argument to find is a . (dot). As soon as I specify a path find does not return anything.

2 files in folder:

~/xtmp/testfind> ls
test1.tmp.txt   test1.txt

expected result by specifying the path as .

~/xtmp/testfind> find . -regex '.*txt.*' ! -regex '.*tmp.*' 
./test1.txt

with $PWD it does not find anything:

~/xtmp/testfind> find $PWD -regex '.*txt.*' ! -regex '.*tmp.*' 
~/xtmp/testfind>

dropping the ! regex it finds everything, so $PWD is correct:

~/xtmp/testfind> find $PWD -regex '.*txt.*' 
[...]/xtmp/testfind/test1.tmp.txt
[...]/xtmp/testfind/test1.txt

Upvotes: 0

Views: 328

Answers (1)

geekosaur
geekosaur

Reputation: 61459

Your path includes the string tmp (as /xtmp/), so the exclusion ! -regex '.*tmp.*' always matches. Negative matching of this kind is very difficult to do properly with regex; but in this case, you probably want to use a glob and -name (which matches only on the final pathname component and not the path leading to it).

find $PWD -name '*txt*' ! -name '*tmp*'

Upvotes: 1

Related Questions