xargs命令的使用过程中一个小领悟:管道与xargs的差别

对xargs的使用总是比较模糊,大概的理解为:通道中,上一个命令的标准输出逐行作为下一个命令的参数

例如 find /var/temp* | xargs rm -r

功效:找出/var/中所有temp开头的文件和文件夹,再用rm逐行删除

(因为rm不支持管道,因此只能用xargs使find的结果逐行作为rm的参数)

假设:

<span style="font-size:18px;">$ find /var/temp*
$ /var/temp1
  /var/temp2</span>
此时,再用xargs rm -r 等效于

<span style="font-size:18px;">$ rm -r /var/temp1
  rm -r /var/temp2</span>

============================分割===================================

那么,管道与xargs有什么差别呢
这是我在使用linux过程中的一个例子。

(find与grep都是支持管道的命令)

<span style="font-size:18px;">#找出/usr/shar/doc中bash-开头的所有文件,结果如下(展开说明前的环境铺垫)
[GMPY@14:44 ~]$find /usr/share/doc/bash-* -type f
/usr/share/doc/bash-completion/AUTHORS
/usr/share/doc/bash-completion/CHANGES.package.old
/usr/share/doc/bash-completion/bash_completion.txt
/usr/share/doc/bash-completion/README
/usr/share/doc/bash-completion/CHANGES
[GMPY@14:45 ~]$
</span>

大家再对比下下面有xargs与无xargs的结果差别

有xargs时的过滤:

<span style="font-size:18px;">[GMPY@14:49 ~]$find /usr/share/doc/bash-* -type f| xargs grep -Ew "README"
/usr/share/doc/bash-completion/bash_completion.txt:    also README.
/usr/share/doc/bash-completion/CHANGES:  * Fix bash_completion paths in README (Debian: #647941)
/usr/share/doc/bash-completion/CHANGES:  * README updated: explain how to use bash-completion correctly.
[GMPY@14:49 ~]$</span>

无xargs时的过滤:

</pre><pre name="code" class="cpp">
<span style="font-size:18px;">[GMPY@14:49 ~]$find /usr/share/doc/bash-* -type f| grep -Ew "README"
/usr/share/doc/bash-completion/README
[GMPY@14:53 ~]$
</span>
结果是不同的,为什么呢?

1、无xargs时是使用管道(虽然严格来说有xargs也是管道,这里为了区分暂时这么称呼),即把find命令的标准输出作为grep的检索内容,等效于:find的结果作为一个“字符串”被grep检索

<span style="font-size:18px;">$ grep -Ew "README" </span>
<span style="font-size:18px;">"/usr/share/doc/bash-completion/AUTHORS
/usr/share/doc/bash-completion/CHANGES.package.old
/usr/share/doc/bash-completion/bash_completion.txt
/usr/share/doc/bash-completion/README
/usr/share/doc/bash-completion/CHANGES"</span>
2、有xargs时,则等效于检索find命令找到的每一个文件
<span style="font-size:18px;">$ grep -Ew "README" /usr/share/doc/bash-completion/AUTHORS
$ grep -Ew "README" /usr/share/doc/bash-completion/CHANGES.package.old
$ grep -Ew "README" /usr/share/doc/bash-completion/bash_completion.txt
$ grep -Ew "README" /usr/share/doc/bash-completion/README
$ grep -Ew "README" /usr/share/doc/bash-completion/CHANGES</span>




posted @ 2015-10-18 14:34  广漠飘羽  阅读(240)  评论(0编辑  收藏  举报