何时在配管时使用xargs? [英] When to use xargs when piping?

查看:95
本文介绍了何时在配管时使用xargs?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对bash并不陌生,我试图了解 xargs 的用法,但对我来说仍然不清楚.例如:

I am new to bash and I am trying to understand the use of xargs, which is still not clear for me. For example:

history | grep ls

在这里,我正在历史记录中搜索命令 ls .在此命令中,我没有使用 xargs ,并且运行良好.

Here I am searching for the command ls in my history. In this command, I did not use xargs and it worked fine.

find /etc - name "*.txt" | xargs ls -l

这是我,我不得不使用 xargs ,但是我仍然无法理解区别,并且我无法正确决定何时使用 xargs 和何时不使用.

I this one, I had to use xargs but I still can not understand the difference and I am not able to decide correctly when to use xargs and when not.

推荐答案

要回答您的问题,当需要从一个命令获取输出并将其用作参数时,可以使用 xargs 其他.在第一个示例中, grep 从标准输入获取数据,而不是将其作为参数.因此,不需要 xargs .

To answer your question, xargs can be used when you need to take the output from one command and use it as an argument to another. In your first example, grep takes the data from standard input, rather than as an argument. So, xargs is not needed.

xargs 从标准输入中获取数据并执行命令.默认情况下,数据作为参数附加到命令的末尾.但是,可以使用占位符作为输入将其插入任何位置.传统的占位符是 {} ;使用该命令,您的示例命令可能会写为:

xargs takes data from standard input and executes a command. By default, the data is appended to the end of the command as an argument. It can be inserted anywhere however, using a placeholder for the input. The traditional placeholder is {}; using that, your example command might then be written as:

find /etc -name "*.txt" | xargs -I {} ls -l {}

如果您在/etc 中有3个文本文件,则将获得每个文件的完整目录列表.当然,您可以轻松编写 ls -l/etc/*.txt 并省去麻烦.

If you have 3 text files in /etc you'll get a full directory listing of each. Of course, you could just have easily written ls -l /etc/*.txt and saved the trouble.

另一个示例可让您重命名这些文件,并要求将占位符 {} 使用两次.

Another example lets you rename those files, and requires the placeholder {} to be used twice.

find /etc -name "*.txt" | xargs -I {} mv {} {}.bak

这两个都是不好的例子,一旦您的文件名包含空格,它们就会中断.您可以通过告诉 find 用空字符分隔文件名来解决此问题.

These are both bad examples, and will break as soon as you have a filename containing whitespace. You can work around that by telling find to separate filenames with a null character.

find /etc -print0 -name "*.txt" | xargs -I {} -0 mv {} {}.bak

我的个人观点是,几乎总是可以使用 xargs 替代方法,而学习这些方法将为您提供更好的服务.

My personal opinion is that there are almost always alternatives to using xargs, and you will be better served by learning those.

这篇关于何时在配管时使用xargs?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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