使用find搜索*.js文件时,如何排除特定目录?
find . -name '*.js'
使用find搜索*.js文件时,如何排除特定目录?
find . -name '*.js'
当前回答
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 \)
其他回答
一个选项是使用grep排除包含目录名的所有结果。例如:
find . -name '*.js' | grep -v excludeddir
对于工作解决方案(在Ubuntu 12.04(精确穿山甲)上测试)。。。
find ! -path "dir1" -iname "*.mp3"
将在当前文件夹和子文件夹(dir1子文件夹除外)中搜索MP3文件。
Use:
find ! -path "dir1" ! -path "dir2" -iname "*.mp3"
…排除dir1和dir2
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
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
但我更喜欢**表示法,以便与其他一些工具保持一致,这在这里可能会偏离主题。