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

find . -name '*.js'

当前回答

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

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

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

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

其他回答

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

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

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

您还可以使用正则表达式包含/排除搜索中的某些文件/目录,具体如下:

find . -regextype posix-egrep -regex ".*\.(js|vue|s?css|php|html|json)$" -and -not -regex ".*/(node_modules|vendor)/.*" 

这将只提供所有js、vue、css等文件,但不包括node_modules和vendor文件夹中的所有文件。

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

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

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

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

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