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

find . -name '*.js'

当前回答

这是因为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

当做

其他回答

如果您正在寻找一个高性能的答案,那么它就是:

find . -type d -name node_modules -prune -false -o -type f

使用-false排除node_modules本身。

在node_modules中包含10000个文件的目录中,它将比非路径方法快3倍。

find . -type f -not -path '*node_modules*'

如果node_modules有更多的文件,您将获得更高的性能。

find . -name '*.js' -\! -name 'glob-for-excluded-dir' -prune

使用多模式-o-name时的另一个示例

在根目录/中搜索所有*.tpl、*.tf文件,不包括位于/src/.traform/和/code/中的文件。

$ find / -type f \( -name '*.tf' -o -name '*.tpl' \) \
  -and \( -not -path '/src/.terraform/*' -and -not -path '/code/*' \)


/src/debug.tf
/src/nodegroup-infra.tpl
/src/variables.tf.tpl

我用hyperfine测试了上述命令;该测试是在具有3k个目录和12k个文件的系统上进行的。我认为可以公平地说,它足够快~70ms

Benchmark #1: ./entrypoint.sh
  Time (mean ± σ):      69.2 ms ±   1.4 ms    [User: 22.6 ms, System: 43.6 ms]
  Range (min … max):    66.4 ms …  72.2 ms    42 runs

目录结构示例

/代码/目录树

bash-5.0# tree /code
/code
├── debug.tf
├── entrypoint.sh
├── nodegroup-infra.tpl
├── tftemplate.sh
└── variables.tf.tpl

0 directories, 5 files

/src/目录树

bash-5.0# tree /src
/src
├── Dockerfile
├── debug.tf
├── entrypoint.sh
├── nodegroup-infra.tpl
├── terraform.tfstate
├── terraform.tfstate.backup
└── variables.tf.tpl

0 directories, 7 files

/根目录树摘要

$ tree /
...
3382 directories, 12164 files

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 . -name '*.js' -not \( -path "./dir1" -o -path "./dir2/*" \)

要添加目录,请添加-o-path“./dirname/*”:

find . -name '*.js' -not \( -path "./dir1" -o -path "./dir2/*" -o -path "./dir3/*"\)

但是,如果有许多目录要排除,也许您应该使用正则表达式。