"{} \;" 是什么意思 在 find 命令中是什么意思?

cod*_*ode 52 command-line find

有时我会看到以下命令:

find . -name  * -exec ls -a {} \;
Run Code Online (Sandbox Code Playgroud)

我被要求执行此操作。

{} \;这里是什么意思?

小智 64

如果您find使用exec,{}扩展到找到的每个文件或目录的文件名find(以便ls在您的示例中将每个找到的文件名作为参数 - 请注意它调用ls或您为每个找到的文件指定一次的任何其他命令)。

分号;结束由 执行的命令exec。需要对其进行转义,\以便您在其中运行的 shellfind不会将其视为自己的特殊字符,而是将其传递给find.

有关更多详细信息,请参阅此文章


此外,find还提供了一些优化exec cmd {} +- 当这样运行时,find将找到的文件附加到命令的末尾,而不是每个文件调用一次(以便命令只运行一次,如果可能的话)。

如果使用 ,则行为的差异(如果不是效率)很容易引起注意ls,例如

find ~ -iname '*.jpg' -exec ls {} \;
# vs
find ~ -iname '*.jpg' -exec ls {} +
Run Code Online (Sandbox Code Playgroud)

假设您有一些jpg文件(路径足够短),则结果是第一种情况下每个文件一行ls,而后一种情况下在列中显示文件的标准行为。

  • 我认为将“\;”与“+”进行对比会对您有所帮助。 (2认同)

Ala*_*Ali 26

命令联机帮助页find联机帮助页图标

-exec command ;
              Execute  command;  true if 0 status is returned.  All following arguments to find are taken to be arguments to
              the command until an argument consisting of `;' is encountered.  The string `{}' is replaced  by  the  current
              file name being processed everywhere it occurs in the arguments to the command, not just in arguments where it
              is alone, as in some versions of find.  Both of these constructions might need to be escaped (with a  `\')  or
              quoted  to  protect them from expansion by the shell.
Run Code Online (Sandbox Code Playgroud)

所以这是解释:

{}表示“的输出find”。就像“find发现的任何东西”一样。find返回您要查找的文件的路径,对吗?所以{}替换它;它是find命令定位的每个文件的占位符(取自此处)。

\;部分基本上是在告诉find“好吧,我已经完成了我想要执行的命令”。

例子:

假设我在一个充满.txt文件的目录中。然后我运行:

find . -name  '*.txt' -exec cat {} \;
Run Code Online (Sandbox Code Playgroud)

第一部分 ,find . -name *.txt返回.txt文件列表。第二部分,-exec cat {} \;将对cat找到的每个文件执行命令find,所以cat file1.txt,,cat file2.txt等等。

  • `*.txt` 部分必须引用为 `'*.txt'`。这是因为如果当前文件夹中有 `.txt` 文件,shell 会展开它,你会得到不正确的结果或错误消息。`find -name '*.txt' -exec cat {} \;` (4认同)