使用find搜索*.js文件时,如何排除特定目录?
find . -name '*.js'
使用find搜索*.js文件时,如何排除特定目录?
find . -name '*.js'
当前回答
我在C源文件exclude*.o和exclude*.swp以及exclude(非常规文件)和exclude-dir输出中找到了函数名:
find . \( ! -path "./output/*" \) -a \( -type f \) -a \( ! -name '*.o' \) -a \( ! -name '*.swp' \) | xargs grep -n soc_attach
其他回答
-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
您可以使用修剪选项来实现这一点。例如:
find ./ -path ./beta/* -prune -o -iname example.com -print
或者反向grep“grep-v”选项:
find -iname example.com | grep -v beta
您可以在Linux find命令exclude directories from search中找到详细的说明和示例。
find -name '*.js' -not -path './node_modules/*' -not -path './vendor/*'
似乎与
find -name '*.js' -not \( -path './node_modules/*' -o -path './vendor/*' \)
并且更容易记住IMO。
要排除多个目录,请执行以下操作:
find . -name '*.js' -not \( -path "./dir1" -o -path "./dir2/*" \)
要添加目录,请添加-o-path“./dirname/*”:
find . -name '*.js' -not \( -path "./dir1" -o -path "./dir2/*" -o -path "./dir3/*"\)
但是,如果有许多目录要排除,也许您应该使用正则表达式。
如果-prune对你不起作用,这将:
find -name "*.js" -not -path "./directory/*"
注意:需要遍历所有不需要的目录。