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

find . -name '*.js'

当前回答

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

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用户的解决方案。我所说的“用户友好”是指只需一次调用,这不需要我记住复杂的语法+我可以使用与以前相同的find语法,因此以下解决方案最适合那些^^^

复制粘贴到shell中,并将~/.bash_aliases作为源代码:

cat << "EOF" >> ~/.bash_aliases
# usage: source ~/.bash_aliases , instead of find type findd + rest of syntax
findd(){
   dir=$1; shift ;
   find  $dir -not -path "*/node_modules/*" -not -path "*/build/*" \
      -not -path "*/.cache/*" -not -path "*/.git/*" -not -path "*/venv/*" $@
}
EOF

当然,为了添加或删除要排除的目录,您必须使用您选择的目录编辑此别名func。。。

您也可以使用

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

这是唯一一个对我有用的。

find / -name MyFile ! -path '*/Directory/*'

正在搜索“MyFile”,不包括“Directory”。强调星星*。

我在C源文件exclude*.o和exclude*.swp以及exclude(非常规文件)和exclude-dir输出中找到了函数名:

find .  \( ! -path "./output/*" \) -a \( -type f \) -a \( ! -name '*.o' \) -a \( ! -name '*.swp' \) | xargs grep -n soc_attach

对于FreeBSD用户:

 find . -name '*.js' -not -path '*exclude/this/dir*'