xargs的时候应该是pferred超过$ P $,而阅读的循环? [英] When should xargs be preferred over while-read loops?

查看:135
本文介绍了xargs的时候应该是pferred超过$ P $,而阅读的循环?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

的xargs 被广泛应用于shell脚本;它通常是很容易使用重铸在bash这些用途同时读取-r;做......做同时读取-ar;做......做循环。

xargs is widely used in shell scripting; it is usually easy to recast these uses in bash using while read -r; do ... done or while read -ar; do ... done loops.

在应的xargs 是preferred,什么时候应该同时读取循环是preferred?

When should xargs be preferred, and when should while-read loops be preferred?

推荐答案

,而事情循环是,他们往往在一次处理一个项目,往往当它的不必要。这是的xargs 有一个优势 - 它可以批量达参数允许一个命令来处理大量的项目

The thing with while loops is that they tend to process one item at a time, often when it's unnecessary. This is where xargs has an advantage - it can batch up the arguments to allow one command to process lots of items.

例如,一个while循环:

For example, a while loop:

pax> echo '1
2
3 
4
5' | while read -r; do echo $REPLY; done
1
2
3
4
5

和相应的的xargs

pax> echo '1
2
3 
4
5' | xargs echo
1 2 3 4 5

在这里,您可以看到线条处理一个接一个具有,而,并完全与的xargs 。换句话说,前者相当于回波1;回音2;回声3;回声4;回声5 而后者则是相当于回声1 2 3 4 5 (五个过程,而不是一个)。这真的有差别处理几千或几万行的时候,因为创作过程需要一定的时间。

Here you can see that the lines are processed one-by-one with the while and altogether with the xargs. In other words, the former is equivalent to echo 1 ; echo 2 ; echo 3 ; echo 4 ; echo 5 while the latter is equivalent to echo 1 2 3 4 5 (five processes as opposed to one). This really makes a difference when processing thousands or tens of thousands of lines, since process creation takes time.

它使用可以接受多个参数,因为它降低了单个进程的数目开始命令时,使事情更快的大多是有利的。

It's mostly advantageous when using commands that can accept multiple arguments since it reduces the number of individual processes started, making things much faster.

当我在加工小文件或在每个项目上运行的命令是复杂的(这里我懒得写一个单独的脚本来给的xargs ) ,我将使用,而变体。

When I'm processing small files or the commands to run on each item are complicated (where I'm too lazy to write a separate script to give to xargs), I will use the while variant.

在哪里我感兴趣的性能(大文件),我将使用的xargs ,即使我必须写一个单独的脚本。

Where I'm interested in performance (large files), I will use xargs, even if I have to write a separate script.

这篇关于xargs的时候应该是pferred超过$ P $,而阅读的循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆