find type -f also returns non-matching files in matching directory

纵饮孤独 提交于 2020-01-07 04:22:08

问题


all files/folders in current directory:

./color_a.txt   
./color_b.txt   
./color_c.txt   
./color/color_d.txt   
./color/blue.txt   
./color/red.txt   
./color/yellow.txt

command used to find all files with the word color in name:

find ./*color* -type f

result:

./color_a.txt   
./color_b.txt   
./color_c.txt   
./color/color_d.txt   
./color/blue.txt   
./color/red.txt   
./color/yellow.txt  

expected result:

./color_a.txt   
./color_b.txt   
./color_c.txt    
./color/color_d.txt    

The result also includes all the non-matching file names under a matching parent directory. How could I get ONLY files with names directly matching the color pattern?

Thanks a lot!


回答1:


What you probably want for filename filtering is a simple -name <glob-pattern> test:

find -name '*color*' -type f

From man find:

 -name pattern
        Base  of  file  name  (the  path with the leading directories removed) matches shell
        pattern pattern.  Because the leading directories are removed, the file names
        considered for a match with -name will never include a  slash,  so `-name a/b' will 
        never match anything (you probably need to use -path instead).

Just as a side note, when you wrote:

find ./*color* -type f

the shell expanded the (unquoted) glob pattern ./*color*, and what was really executed (what find saw) was this:

find ./color ./color_a.txt ./color_b.txt ./color_c.txt -type f

thus producing a list of files in all of those locations.




回答2:


You can use the regex option

find -regex ".*color_.*" -type f


来源:https://stackoverflow.com/questions/44995142/find-type-f-also-returns-non-matching-files-in-matching-directory

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!