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

find . -name '*.js'

当前回答

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

但我更喜欢**表示法,以便与其他一些工具保持一致,这在这里可能会偏离主题。

其他回答

您也可以使用

find  -type f -not -name .directoryname -printf "%f\n"

这是我用来排除某些路径的格式:

$ find ./ -type f -name "pattern" ! -path "excluded path" ! -path "excluded path"

我使用此命令查找不在“.*”路径中的所有文件:

$ find ./ -type f -name "*" ! -path "./.*" ! -path "./*/.*"

这适合我在Mac上使用:

find . -name *.php -or -path "./vendor" -prune -or -path "./app/cache" -prune

它将排除带有php后缀的搜索名称的供应商和app/cache-dir。

我使用find为xgettext提供文件列表,并希望省略特定目录及其内容。我尝试了许多-path与-prune组合的排列,但无法完全排除我想要删除的目录。

虽然我能够忽略我想要忽略的目录内容,但find随后将目录本身作为结果之一返回,结果导致xgettext崩溃(不接受目录,只接受文件)。

我的解决方案是简单地使用grep-v跳过结果中不需要的目录:

find /project/directory -iname '*.php' -or -iname '*.phtml' | grep -iv '/some/directory' | xargs xgettext

我不能肯定,是否有一个论据支持这一发现,它能100%奏效。在头痛之后,使用grep是一个快速而简单的解决方案。

我想知道目录的数量,文件的大小(仅为当前目录的MB),而这段代码正是我想要的:-)

来源

- ...    2791037 Jun  2  2011 foo.jpg
- ... 1284734651 Mär 10 16:16 foo.tar.gz
- ...          0 Mär 10 15:28 foo.txt
d ...       4096 Mär  3 17:12 HE
d ...       4096 Mär  3 17:21 KU
d ...       4096 Mär  3 17:17 LE
d ...          0 Mär  3 17:14 NO
d ...          0 Mär  3 17:15 SE
d ...          0 Mär  3 17:13 SP
d ...          0 Mär  3 17:14 TE
d ...          0 Mär  3 19:20 UN

代码

format="%s%'12d\n"

find . -type d -not -path "./*/*" | wc -l | awk -v fmt=$format '{printf fmt, " Anzahl Ordner  = ", $1-1}'
find . -type f -not -path "./*/*" | wc -l | awk -v fmt=$format '{printf fmt, " Anzahl Dateien = ", $1}'
  du . -hmS --max-depth=0 | awk -v fmt=$format '{printf fmt, " Groesse (MB)   = ", $1}'

注意:awk需要额外的format=“%s%12d\n”来格式化数字。

结果

Anzahl Ordner  =            8
Anzahl Dateien =            3
Groesse (MB)   =        1.228