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

find . -name '*.js'

当前回答

对于我所需要的,它是这样工作的,从root开始在所有服务器中查找landscape.jpg,不包括/var目录中的搜索:

find/-maxdepth 1-type d | grep-v/var | xargs-I“{}”find“{}”-name landscape.jpg

find/-maxdepth 1-type d列出/

grep-v/var从列表中排除“/var”

xargs-I“{}”find“{}”-name landscape.jpg执行任何命令,如find with each directory/result from list

其他回答

-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

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 \)  

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

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

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

这适合我在Mac上使用:

find . -name *.php -or -path "./vendor" -prune -or -path "./app/cache" -prune

它将排除带有php后缀的搜索名称的供应商和app/cache-dir。