使用find搜索*.js文件时,如何排除特定目录?
find . -name '*.js'
使用find搜索*.js文件时,如何排除特定目录?
find . -name '*.js'
当前回答
我认为自己是一个狂欢爱好者,但是。。。在过去的两年中,我们没有找到一个适合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。。。
其他回答
我在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
如果有人在研究如何同时忽略多条路径。您可以使用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/目录路径。
而不是:
for file in $(find . -name '*.js')
do
java -jar config/yuicompressor-2.4.2.jar --type js $file -o $file
done
…并且由于您没有定义要排除的子目录,因此可以使用:
for file in $(find *.js -maxdepth 0 -name '*.js')
do
java -jar config/yuicompressor-2.4.2.jar --type js $file -o $file
done
此语法将排除所有子目录。
看看下面的示例:在tmp目录下,我有一个巨大的“归档”子目录,其中包含17000-4640=12360个文件。此目录位于慢速NFS上。虽然第一个语法扫描“archive”子目录并执行得很差,但第二个语法只扫描我当前目录中包含的“*pdf”文件并执行。。。没那么糟。
[tmp]$ time (find . -name "*pdf" | wc -l)
17000
real 0m40.479s
user 0m0.423s
sys 0m5.606s
[tmp]$ time (find *pdf -maxdepth 0 -name "*pdf" | wc -l)
4640
real 0m7.778s
user 0m0.113s
sys 0m1.136s
第二种语法非常有趣:在下面的示例中,我想检查文件or60runm50958.pdf是否存在,并且超过20分钟。亲自看看第二种语法是如何更有效的。这是因为它避免了扫描存档子目录。
[tmp]$ time find . -name or60runm50958.pdf -mmin +20
./or60runm50958.pdf
real 0m51.145s
user 0m0.529s
sys 0m6.243s
[tmp]$ time find or60runm50958.pdf -maxdepth 0 -name or60runm50958.pdf -mmin +20
or60runm50958.pdf
real 0m0.004s
user 0m0.000s
sys 0m0.002s
使用-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”开头的子目录。