使用find搜索*.js文件时,如何排除特定目录?
find . -name '*.js'
使用find搜索*.js文件时,如何排除特定目录?
find . -name '*.js'
当前回答
您还可以使用正则表达式包含/排除搜索中的某些文件/目录,具体如下:
find . -regextype posix-egrep -regex ".*\.(js|vue|s?css|php|html|json)$" -and -not -regex ".*/(node_modules|vendor)/.*"
这将只提供所有js、vue、css等文件,但不包括node_modules和vendor文件夹中的所有文件。
其他回答
使用-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
最好使用exec操作而不是for循环:
find . -path "./dirtoexclude" -prune \
-o -exec java -jar config/yuicompressor-2.4.2.jar --type js '{}' -o '{}' \;
执行者…'{}' ... '{}' \; 将对每个匹配的文件执行一次,将大括号“{}”替换为当前文件名。
请注意,大括号括在单引号中,以防止它们被解释为shell脚本标点符号*。
笔记
*从find(GNU findutils)4.4.2手册页的EXAMPLES部分
这是唯一一个对我有用的。
find / -name MyFile ! -path '*/Directory/*'
正在搜索“MyFile”,不包括“Directory”。强调星星*。
使用-prune选项。因此,类似于:
find . -type d -name proc -prune -o -name '*.js'
“-typed-name-proc-prune”只查找要排除的名为proc的目录。“-o”是“OR”运算符。
您可以使用修剪选项来实现这一点。例如:
find ./ -path ./beta/* -prune -o -iname example.com -print
或者反向grep“grep-v”选项:
find -iname example.com | grep -v beta
您可以在Linux find命令exclude directories from search中找到详细的说明和示例。