使用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 \)
其他回答
使用-prune选项。因此,类似于:
find . -type d -name proc -prune -o -name '*.js'
“-typed-name-proc-prune”只查找要排除的名为proc的目录。“-o”是“OR”运算符。
一个选项是使用grep排除包含目录名的所有结果。例如:
find . -name '*.js' | grep -v excludeddir
对于FreeBSD用户:
find . -name '*.js' -not -path '*exclude/this/dir*'
如何在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
我在这个页面上找到了建议,很多其他页面在我的Mac OS X系统上都不起作用。然而,我发现了一种对我有用的变体。
大的想法是搜索Macintosh HD,但避免遍历所有外部卷,这些卷主要是Time Machine备份、映像备份、装载的共享和存档,但不必全部卸载,这通常是不切实际的。
这是我的工作脚本,我将其命名为“findit”。
#!/usr/bin/env bash
# inspired by http://stackoverflow.com/questions/4210042/exclude-directory-from-find-command Danile C. Sobral
# using special syntax to avoid traversing.
# However, logic is refactored because the Sobral version still traverses
# everything on my system
echo ============================
echo find - from cwd, omitting external volumes
date
echo Enter sudo password if requested
sudo find . -not \( \
-path ./Volumes/Archive -prune -o \
-path ./Volumes/Boot\ OS\ X -prune -o \
-path ./Volumes/C \
-path ./Volumes/Data -prune -o \
-path ./Volumes/jas -prune -o \
-path ./Volumes/Recovery\ HD -prune -o \
-path ./Volumes/Time\ Machine\ Backups -prune -o \
-path ./Volumes/SuperDuper\ Image -prune -o \
-path ./Volumes/userland -prune \
\) -name "$1" -print
date
echo ============================
iMac2:~ jas$
不同的路径与外部存档卷、Time Machine、虚拟机、其他装载的服务器等有关。一些卷名中有空格。
一个好的测试运行是“finditindex.php”,因为该文件出现在我的系统中的许多地方。使用此脚本,搜索主硬盘大约需要10分钟。如果没有这些例外,这需要很多小时。