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

find . -name '*.js'

当前回答

如果有人想在Makefile中添加find命令,下面是我们排除目录的方法

! -路径“*/directoryName/*”

以下是格式化所有golang文件的示例,不包括protobuf go文件和供应商目录下的所有文件:

find . ! -name '*.pb.go' -name '*.go' ! -path "*/vendor/*" -exec gofmt -s -w '{}' +

其他回答

我发现以下内容比其他建议的解决方案更容易理解:

find build -not \( -path build/external -prune \) -name \*.js
# you can also exclude multiple paths
find build -not \( -path build/external -prune \) -not \( -path build/blog -prune \) -name \*.js

重要提示:在-path之后键入的路径必须与find在没有排除的情况下打印的路径完全匹配。如果这句话让您感到困惑,您只需确保在整个命令中使用完整路径,如下所示:find/full/path/-not\(-path/full/path/exclude/this-sprune\)。。。。如果您想更好地理解,请参见注释[1]。

Inside\(和\)是一个表达式,它将与build/external完全匹配(请参见上面的重要注释),并且在成功后,将避免遍历下面的任何内容。然后将其分组为带有转义括号的单个表达式,并以-not作为前缀,这将使find跳过该表达式匹配的任何内容。

有人可能会问,添加-not是否不会使所有其他被-previe隐藏的文件重新出现,答案是否定的。

这来自一个实际的用例,我需要对温特史密斯生成的一些文件调用yui压缩程序,但忽略了需要按原样发送的其他文件。


注[1]:如果您想排除/tmp/foo/bar,并且运行find时类似于“find/tmp\(…)”,那么您必须指定-path/tmp/foo/bar。另一方面,如果您运行find,类似于cd/tmp;find.\(…),那么必须指定-path。/foo/bbar。

您可以使用修剪选项来实现这一点。例如:

find ./ -path ./beta/* -prune -o -iname example.com -print

或者反向grep“grep-v”选项:

find -iname example.com | grep -v beta

您可以在Linux find命令exclude directories from search中找到详细的说明和示例。

如果有人在研究如何同时忽略多条路径。您可以使用bash数组(在GNUbash版本4.4.20(1)-发行版上运行良好)

#!/usr/bin/env bash

# This script helps ignore unnecessary dir paths while using the find command

EXCLUDE_DIRS=(
    "! -path /*.git/*"
    "! -path /*go/*"
    "! -path /*.bundle/*"
    "! -path /*.cache/*"
    "! -path /*.local/*"
    "! -path /*.themes/*"
    "! -path /*.config/*"
    "! -path /*.codeintel/*"
    "! -path /*python2.7/*"
    "! -path /*python3.6/*"
    "! -path /*__pycache__/*"
)
find $HOME -type f ${EXCLUDE_DIRS[@]}

# if you like fzf

find $HOME -type f ${EXCLUDE_DIRS[@]} | fzf --height 40% --reverse

同样由于某些原因,您将无法忽略/bin/目录路径。

不确定这是否能涵盖所有边缘情况,但以下内容将非常简单明了:

ls-1 | grep-v-e ddl-e docs | xargs rm-rf

这将从当前目录excpet“ddls”和“docs”中删除所有文件/目录。

以下命令有效:

find . -path ./.git -prune -o -print

如果查找有问题,请使用-D树选项查看表达式分析信息。

find -D tree . -path ./.git -prune -o -print

或者使用-D all,查看所有执行信息。

find -D all . -path ./.git -prune -o -print