使用find搜索*.js文件时,如何排除特定目录?

find . -name '*.js'

当前回答

您还可以使用正则表达式包含/排除搜索中的某些文件/目录,具体如下:

find . -regextype posix-egrep -regex ".*\.(js|vue|s?css|php|html|json)$" -and -not -regex ".*/(node_modules|vendor)/.*" 

这将只提供所有js、vue、css等文件,但不包括node_modules和vendor文件夹中的所有文件。

其他回答

您也可以使用

find  -type f -not -name .directoryname -printf "%f\n"

以前的答案在Ubuntu上都不好。试试看:

find . ! -path "*/test/*" -type f -name "*.js" ! -name "*-min-*" ! -name "*console*"

我在这里找到了这个

path-prune方法还可以处理路径中的通配符。下面是一个find语句,它将查找服务于多个git存储库的git服务器的目录,而不包括git内部目录:

find . -type d \
   -not \( -path */objects -prune \) \
   -not \( -path */branches -prune \) \
   -not \( -path */refs -prune \) \
   -not \( -path */logs -prune \) \
   -not \( -path */.git -prune \) \
   -not \( -path */info -prune \) \
   -not \( -path */hooks -prune \)  

-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

如果-prune对你不起作用,这将:

find -name "*.js" -not -path "./directory/*"

注意:需要遍历所有不需要的目录。