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

find . -name '*.js'

当前回答

使用多模式-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

其他回答

对于工作解决方案(在Ubuntu 12.04(精确穿山甲)上测试)。。。

find ! -path "dir1" -iname "*.mp3"

将在当前文件夹和子文件夹(dir1子文件夹除外)中搜索MP3文件。

Use:

find ! -path "dir1" ! -path "dir2" -iname "*.mp3"

…排除dir1和dir2

find . \( -path '.**/.git' -o -path '.**/.hg' \) -prune -o -name '*.js' -print

上面的示例查找当前目录下的所有*.js文件,不包括文件夹.git和.hg,无论这些.git和.h文件夹有多深。

注意:这也适用于:

find . \( -path '.*/.git' -o -path '.*/.hg' \) -prune -o -name '*.js' -print

但我更喜欢**表示法,以便与其他一些工具保持一致,这在这里可能会偏离主题。

要排除多个目录,请执行以下操作:

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

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

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

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

我使用find为xgettext提供文件列表,并希望省略特定目录及其内容。我尝试了许多-path与-prune组合的排列,但无法完全排除我想要删除的目录。

虽然我能够忽略我想要忽略的目录内容,但find随后将目录本身作为结果之一返回,结果导致xgettext崩溃(不接受目录,只接受文件)。

我的解决方案是简单地使用grep-v跳过结果中不需要的目录:

find /project/directory -iname '*.php' -or -iname '*.phtml' | grep -iv '/some/directory' | xargs xgettext

我不能肯定,是否有一个论据支持这一发现,它能100%奏效。在头痛之后,使用grep是一个快速而简单的解决方案。

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