Linux find -exec cmd {} + vs | 参数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/896808/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-03 17:20:30  来源:igfitidea点击:

find -exec cmd {} + vs | xargs

linuxunixcommand-linefind

提问by dogbane

Which one is more efficient over a very large set of files and should be used?

哪一个在非常大的文件集上更有效,应该使用?

find . -exec cmd {} +

or

或者

find . | xargs cmd

(Assume that there are no funny characters in the filenames)

(假设文件名中没有有趣的字符)

采纳答案by Tometzky

Speed difference will be insignificant.

速度差异将是微不足道的。

But you have to make sure that:

但你必须确保:

  1. Your script will not assume that no file will have space, tab, etc in file name; the first version is safe, the second is not.

  2. Your script will not treat a file starting with "-" as an option.

  1. 您的脚本不会假设文件名中没有空格、制表符等;第一个版本是安全的,第二个不是。

  2. 您的脚本不会将以“ -”开头的文件视为选项。

So your code should look like this:

所以你的代码应该是这样的:

find . -exec cmd -option1 -option2 -- {} +

or

或者

find . -print0 | xargs -0 cmd -option1 -option2 --

The first version is shorter and easier to write as you can ignore 1, but the second version is more portable and safe, as "-exec cmd {} +" is a relatively new option in GNU findutils (since 2005, lots of running systems will not have it yet) and it was buggy recently. Also lots of people do not know this "-exec cmd {} +", as you can see from other answers.

第一个版本更短更容易编写,因为您可以忽略 1,但第二个版本更便携和安全,因为“ -exec cmd {} +”是 GNU findutils 中相对较新的选项(自 2005 年以来,许多正在运行的系统还没有它)而且最近有问题。还有很多人不知道这个“ -exec cmd {} +”,正如您从其他答案中看到的那样。

回答by ASk

find . | xargs cmd

is more efficient (it runs cmdas few times as possible, unlike exec, which runs cmdonce for each match). However, you will run into trouble if filenames contain spaces or funky characters.

效率更高(它运行的cmd次数越少越好,不像exec,它cmd为每个匹配运行一次)。但是,如果文件名包含空格或时髦的字符,您会遇到麻烦。

The following is suggested to be used:

建议使用以下方法:

find . -print0 | xargs -0 cmd

this will work even if filenames contain funky characters (-print0makes findprint NUL-terminated matches, -0makes xargsexpect this format.)

即使文件名包含时髦的字符,这也会起作用(-print0使find打印以 NUL 结尾的匹配,-0使xargs期望这种格式。)

回答by poige

Modern xargs's versions often support parallel pipeline execution.

Modernxargs的版本通常支持并行管道执行。

Obviously it might be a pivot point when it comes to choice between find … -execand … | xargs

显然,这可能是在 find … -exec… | xargs