使用find搜索*.js文件时,如何排除特定目录?
find . -name '*.js'
使用find搜索*.js文件时,如何排除特定目录?
find . -name '*.js'
当前回答
-prune绝对有效,并且是最好的答案,因为它可以防止下降到要排除的目录中-not-path仍然搜索排除的目录,它只是不打印结果,如果排除的目录已装入网络卷或您没有权限,这可能是一个问题。
棘手的是,find对参数的顺序非常讲究,所以如果你不能正确地获取它们,你的命令可能无法正常工作。论点的顺序一般如下:
find {path} {options} {action}
{path}:首先放置所有与路径相关的参数,如-路径'/dir1'-修剪-o
{options}:将-name、-iname等作为此组中的最后一个选项时,我最成功。例如-type f-iname“*.js”
{action}:使用-prine时需要添加-print
下面是一个工作示例:
# setup test
mkdir dir1 dir2 dir3
touch dir1/file.txt; touch dir1/file.js
touch dir2/file.txt; touch dir2/file.js
touch dir3/file.txt; touch dir3/file.js
# search for *.js, exclude dir1
find . -path './dir1' -prune -o -type f -iname '*.js' -print
# search for *.js, exclude dir1 and dir2
find . \( -path './dir1' -o -path './dir2' \) -prune -o -type f -iname '*.js' -print
其他回答
如何在sh中使用find的prune选项是Laurence Gonsalves关于prune如何工作的一个很好的答案。
下面是通用解决方案:
find /path/to/search \
-type d \
\( -path /path/to/search/exclude_me \
-o \
-name exclude_me_too_anywhere \
\) \
-prune \
-o \
-type f -name '*\.js' -print
要避免多次键入/path/To/seach/,请将查找包装在pushd中。。popd对。
pushd /path/to/search; \
find . \
-type d \
\( -path ./exclude_me \
-o \
-name exclude_me_too_anywhere \
\) \
-prune \
-o \
-type f -name '*\.js' -print; \
popd
我使用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 . \( -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
但我更喜欢**表示法,以便与其他一些工具保持一致,这在这里可能会偏离主题。
使用-prune选项。因此,类似于:
find . -type d -name proc -prune -o -name '*.js'
“-typed-name-proc-prune”只查找要排除的名为proc的目录。“-o”是“OR”运算符。
find -name '*.js' -not -path './node_modules/*' -not -path './vendor/*'
似乎与
find -name '*.js' -not \( -path './node_modules/*' -o -path './vendor/*' \)
并且更容易记住IMO。