使用find搜索*.js文件时,如何排除特定目录?
find . -name '*.js'
使用find搜索*.js文件时,如何排除特定目录?
find . -name '*.js'
当前回答
对于那些在旧版本UNIX上无法使用-path或-not的用户
在SunOS 5.10 bash 3.2和SunOS 5.11 bash 4.4上测试
find . -type f -name "*" -o -type d -name "*excluded_directory*" -prune -type f
其他回答
-prune绝对有效,并且是最好的答案,因为它可以防止下降到要排除的目录中-not-path仍然搜索排除的目录,它只是不打印结果,如果排除的目录已装入网络卷或您没有权限,这可能是一个问题。
棘手的是,find对参数的顺序非常讲究,所以如果你不能正确地获取它们,你的命令可能无法正常工作。论点的顺序一般如下:
find {path} {options} {action}
{path}:首先放置所有与路径相关的参数,如-路径'/dir1'-修剪-o
{options}:将-name、-iname等作为此组中的最后一个选项时,我最成功。例如-type f-iname“*.js”
{action}:使用-prine时需要添加-print
下面是一个工作示例:
# setup test
mkdir dir1 dir2 dir3
touch dir1/file.txt; touch dir1/file.js
touch dir2/file.txt; touch dir2/file.js
touch dir3/file.txt; touch dir3/file.js
# search for *.js, exclude dir1
find . -path './dir1' -prune -o -type f -iname '*.js' -print
# search for *.js, exclude dir1 and dir2
find . \( -path './dir1' -o -path './dir2' \) -prune -o -type f -iname '*.js' -print
对于那些在旧版本UNIX上无法使用-path或-not的用户
在SunOS 5.10 bash 3.2和SunOS 5.11 bash 4.4上测试
find . -type f -name "*" -o -type d -name "*excluded_directory*" -prune -type f
对于FreeBSD用户:
find . -name '*.js' -not -path '*exclude/this/dir*'
一个选项是使用grep排除包含目录名的所有结果。例如:
find . -name '*.js' | grep -v excludeddir
这是因为find测试模式“*foo*”的文件:
find ! -path "dir1" ! -path "dir2" -name "*foo*"
但如果不使用模式(find不测试文件),它就不起作用。因此find没有使用它以前评估的“true”和“false”布尔值。不使用上述符号的用例示例:
find ! -path "dir1" ! -path "dir2" -type f
没有找到测试!因此,如果您需要查找没有任何模式匹配的文件,请使用-prune。此外,通过使用prune查找总是更快,因为它确实跳过了该目录,而不是匹配它或更好地不匹配它
find dir -not \( -path "dir1" -prune \) -not \( -path "dir2" -prune \) -type f
or:
find dir -not \( -path "dir1" -o -path "dir2" -prune \) -type f
当做