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

find . -name '*.js'

当前回答

您也可以使用

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

其他回答

-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

如果-prune对你不起作用,这将:

find -name "*.js" -not -path "./directory/*"

注意:需要遍历所有不需要的目录。

有很多好的答案,我只是花了一些时间来理解命令的每个元素是什么以及背后的逻辑。

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

find将开始查找当前目录中的文件和目录,因此查找。。

-o选项代表逻辑OR,并将命令的两部分分开:

[ -path ./misc -prune ] OR [ -name '*.txt' -print ]

不是的任何目录或文件/misc目录不会通过第一个测试路径/其他。但他们将根据第二个表达式进行测试。如果它们的名称与模式*.txt相对应,则会因为-print选项而被打印。

当find到达时/misc目录,此目录仅满足第一个表达式。因此,将对其应用-prune选项。它告诉find命令不要浏览该目录。中的任何文件或目录/find甚至不会探索misc,不会针对表达式的第二部分进行测试,也不会打印。

如果有人在研究如何同时忽略多条路径。您可以使用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/目录路径。