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

find . -name '*.js'

当前回答

如何在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 . -path ./.git -prune -o -print

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

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

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

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

使用-prune主键。例如,如果要排除/其他:

find . -path ./misc -prune -o -name '*.txt' -print

要排除多个目录,请在括号中对它们进行“或”运算。

find . -type d \( -path ./dir1 -o -path ./dir2 -o -path ./dir3 \) -prune -o -name '*.txt' -print

而且,要在任何级别排除具有特定名称的目录,请使用-name primary而不是-path。

find . -type d -name node_modules -prune -o -name '*.json' -print

如果搜索目录有模式(在大多数情况下);您可以简单地如下所示:

find ./n* -name "*.tcl" 

在上述示例中;它搜索所有以“n”开头的子目录。

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 \)  

我想知道目录的数量,文件的大小(仅为当前目录的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