使用“-prune”时,从“find”命令中省略“-print”

Pap*_*Bob 6 bash find

我一直无法完全理解 find 命令的 -prune 操作。但实际上,至少我的一些误解源于省略“-print”表达的影响。

从“查找”手册页..

“如果表达式除 -prune 之外不包含任何操作,则对表达式为 true 的所有文件执行 -print。”

..我一直(多年来)认为这意味着我可以省略“-print”。

但是,如以下示例所示,使用“-print”和省略“-print”之间存在差异,至少在出现“-prune”表达式时是这样。

首先,我的工作目录下有以下8个目录..

aqua/
aqua/blue/
blue/
blue/orange/
blue/red/
cyan/blue/
green/
green/yellow/
Run Code Online (Sandbox Code Playgroud)

这8个目录下总共有10个文件。

aqua/blue/config.txt
aqua/config.txt
blue/config.txt
blue/orange/config.txt
blue/red/config.txt
cyan/blue/config.txt
green/config.txt
green/test.log
green/yellow/config.txt
green/yellow/test.log
Run Code Online (Sandbox Code Playgroud)

我的目标是使用“查找”来显示文件路径中不包含“蓝色”的所有常规文件。有五个文件符合此要求。

这按预期工作..

% find . -path '*blue*' -prune -o -type f -print
./green/test.log
./green/yellow/config.txt
./green/yellow/test.log
./green/config.txt
./aqua/config.txt
Run Code Online (Sandbox Code Playgroud)

但是,当我省略“-print”时,它不仅返回五个所需的文件,而且还返回路径名包含“blue”的任何目录。

% find . -path '*blue*' -prune -o -type f
./green/test.log
./green/yellow/config.txt
./green/yellow/test.log
./green/config.txt
./cyan/blue
./blue
./aqua/blue
./aqua/config.txt
Run Code Online (Sandbox Code Playgroud)

那么为什么会显示三个“蓝色”目录呢?

这可能很重要,因为我经常尝试删除包含超过 50,000 个文件的目录结构。当处理该路径时,我的 find 命令,特别是如果我对每个文件执行“-exec grep”,可能会花费大量时间来处理我完全不感兴趣的文件。我需要确信 find 不会进入修剪后的结构。

eph*_*ent 2

隐式-print适用于整个表达式,而不仅仅是它的最后一部分。

% find . \( -path '*blue*' -prune -o -type f \) -print
./green/test.log
./green/yellow/config.txt
./green/yellow/test.log
./green/config.txt
./cyan/blue
./blue
./aqua/blue
./aqua/config.txt
Run Code Online (Sandbox Code Playgroud)

它不会下降到修剪的目录中,但会打印出顶层。

稍作修改:

$ find . ! \( -path '*blue*' -prune \) -type f
./green/test.log
./green/yellow/config.txt
./green/yellow/test.log
./green/config.txt
./aqua/config.txt
Run Code Online (Sandbox Code Playgroud)

(使用隐式-a)将导致使用和不使用时具有相同的行为-print