使用find搜索*.js文件时,如何排除特定目录?
find . -name '*.js'
使用find搜索*.js文件时,如何排除特定目录?
find . -name '*.js'
当前回答
这是我用来排除某些路径的格式:
$ find ./ -type f -name "pattern" ! -path "excluded path" ! -path "excluded path"
我使用此命令查找不在“.*”路径中的所有文件:
$ find ./ -type f -name "*" ! -path "./.*" ! -path "./*/.*"
其他回答
使用多模式-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
对于我所需要的,它是这样工作的,从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
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
但我更喜欢**表示法,以便与其他一些工具保持一致,这在这里可能会偏离主题。
我认为自己是一个狂欢爱好者,但是。。。在过去的两年中,我们没有找到一个适合bash用户的解决方案。我所说的“用户友好”是指只需一次调用,这不需要我记住复杂的语法+我可以使用与以前相同的find语法,因此以下解决方案最适合那些^^^
复制粘贴到shell中,并将~/.bash_aliases作为源代码:
cat << "EOF" >> ~/.bash_aliases
# usage: source ~/.bash_aliases , instead of find type findd + rest of syntax
findd(){
dir=$1; shift ;
find $dir -not -path "*/node_modules/*" -not -path "*/build/*" \
-not -path "*/.cache/*" -not -path "*/.git/*" -not -path "*/venv/*" $@
}
EOF
当然,为了添加或删除要排除的目录,您必须使用您选择的目录编辑此别名func。。。
如果搜索目录有模式(在大多数情况下);您可以简单地如下所示:
find ./n* -name "*.tcl"
在上述示例中;它搜索所有以“n”开头的子目录。