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

find . -name '*.js'

当前回答

一个选项是使用grep排除包含目录名的所有结果。例如:

find . -name '*.js' | grep -v excludeddir

其他回答

不确定这是否能涵盖所有边缘情况,但以下内容将非常简单明了:

ls-1 | grep-v-e ddl-e docs | xargs rm-rf

这将从当前目录excpet“ddls”和“docs”中删除所有文件/目录。

对于工作解决方案(在Ubuntu 12.04(精确穿山甲)上测试)。。。

find ! -path "dir1" -iname "*.mp3"

将在当前文件夹和子文件夹(dir1子文件夹除外)中搜索MP3文件。

Use:

find ! -path "dir1" ! -path "dir2" -iname "*.mp3"

…排除dir1和dir2

我认为自己是一个狂欢爱好者,但是。。。在过去的两年中,我们没有找到一个适合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。。。

使用-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 . -name '*.js' -\! -name 'glob-for-excluded-dir' -prune