理解 UNIX 命令 xargs [英] Understanding the UNIX command xargs

查看:33
本文介绍了理解 UNIX 命令 xargs的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对此非常困惑.需要澄清一下.

I'm pretty much confused on this. Need some clarifications.

示例 1:

pgrep string | xargs ps

示例 2:

find . | xargs grep whatever

从示例 1 中,我认为是这样的:

From Example 1, I gather it's this way:

搜索作为正在运行的进程名称的一部分的字符串",并将所有匹配项的进程 ID 返回到 'xargs ps' -> 它将 ps 附加到匹配项(它们本身就是进程 ID)到获得与以下相同的输出:

Search for a "string" which is part of name of running process and return the process-ids of all the matches to 'xargs ps' -> which just appends ps to the matches (which are process-ids themselves) to get the same output as :

ps <processid>

有人能解释一下 xargs 在这种情况下的真正作用吗?

Can someone explain what xargs really does in this case?

从示例 2 中,我认为是这样的:

From Example 2, I gather it's this way:

它是从当前工作目录递归搜索一些字符串".在这里,xargs"究竟是如何工作的?

It's to search for some "string" recursively from the current working directory. Here, how exactly does 'xargs' work?

我认为 'xargs' 会反复将标准输入中的数据附加到提供给 xargs 的 'argument'(它本身通常是一个 UNIX 命令).

I was of the opinion that 'xargs' repeatedly appends data from standard input to the 'argument' given to xargs (which usually is a UNIX command by itself).

来自 xargs() 手册页:

From xargs() man page :

xargs 从标准输入读取项目,以空格分隔(可以是用双引号或单引号或反斜杠保护)或换行符,以及执行命令(默认为/bin/echo)一次或多次初始参数后跟从标准输入读取的项目.空行忽略标准输入.

xargs reads items from the standard input, delimited by blanks (which can be protected with double or single quotes or a backslash) or newlines, and executes the command (default is /bin/echo) one or more times with any initial-arguments followed by items read from standard input. Blank lines on the standard input are ignored.

推荐答案

一般xargs是这样使用的

prog |xargs 实用程序

其中 prog 预期输出一个或多个换行符/空格分隔的结果.诀窍在于 xargs 不一定为每个结果调用一次 utility,而是将结果拆分为子列表并为每个子列表调用 utility.如果您想强制 xargs 为每个结果调用 utility,您需要使用 xargs -L1 调用它.

where prog is expected to output one or more newline/space separated results. The trick is that xargs does not necessarily call utility once for each result, instead it splits the results into sublists and calls utility for every sublist. If you want to force xargs to call utility for every single result you will need to invoke it with xargs -L1.

注意 xargs 向你保证发送到 utility 的子列表比 ARG_MAX 短(如果你好奇,你可以得到ARG_MAX 的当前值使用 getconf ARG_MAX.)这就是它如何避免那些可怕的参数列表太长" 错误.

Note that xargs promises you that the sublist sent to utility is shorter than ARG_MAX (If you're curious, you can get the current value of ARG_MAX using getconf ARG_MAX.) This is how it avoids those dreaded "Argument list to long" errors.

这篇关于理解 UNIX 命令 xargs的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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