xargs、管道、exec区别

作者:ilexwg
链接:https://www.zhihu.com/question/27452459/answer/170834758
来源:知乎
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

管道和xargs不是一回事

-1- 管道只是将前面的标准输出作为后面的标准输入,而不能将前面的标准输出作为后面的命令参数;

-2- xargs能够将前面的标准输出作为后面的命令参数


===== 给你举个例子 =====


文本文件china.txt的内容如下

[root@elephant tmp]# cat china.txt 
Hello Beijing

如果我们只用管道符执行下面命令

[root@elephant tmp]# echo china.txt | cat
china.txt

我们看到cat命令并没有识别出管道传给他的"china.txt"是一个命令参数(文件名),而当成了一般文本了

下面看看加上xargs输出了什么

[root@elephant tmp]# echo china.txt | xargs cat
Hello Beijing

得到了我们预期的效果了,cat命令将"china.txt"是一个命令参数(文件名),打印出了"china.txt"文本文件中的文本内容


其实从xargs的字面也可以理解,xargs就是"execute arguments"的缩写,它的作用就是从标准输入中读取内容,并将此内容传递给它后面的命令,并作为那个命令的参数来执行

xargs与exec的区别

(1)exec参数是一个一个传递的,传递一个参数执行一次命令;xargs一次将参数传给命令,可以使用-n控制参数个数

[root@localhost] ~$ find . -name '*.txt' -type f | xargs echo begin  
begin ./xargs.txt ./temp.txt ./china.txt ./num.txt ./out.txt
[root@localhost] ~$ find . -name '*.txt' -type f -exec echo begin {} ;  
begin ./xargs.txt
begin ./temp.txt
begin ./china.txt
begin ./num.txt
begin ./out.txt

(2)exec文件名有空格等特殊字符也能处理;xargs不能处理特殊文件名,如果想处理特殊文件名需要特殊处理

[root@localhost] ~$ find . -name 't t.txt' -type f | xargs cat  
a b c d e f g   
h i j k l m n   
o p q  
r s t  
u v w x y z
cat: t.txt: No such file or directory
[root@localhost] ~$ find . -name 't t.txt' -type f -exec cat {} ;  
a b c d e f g   
h i j k l m n   
o p q  
r s t  
u v w x y z

原因:默认情况下, find 每输出一个文件名, 后面都会接着输出一个换行符 (' '),因此我们看到的 find 的输出都是一行一行的,xargs 默认是以空白字符 (空格, TAB, 换行符) 来分割记录的, 因此文件名 ./t t.txt 被解释成了两个记录 ./t 和 t.txt, cat找不到这两个文件,所以报错,为了解决此类问题,  让 find 在打印出一个文件名之后接着输出一个 NULL 字符 ('') 而不是换行符, 然后再告诉 xargs 也用 NULL 字符来作为记录的分隔符,即 find -print0 和 xargs -0 ,这样就能处理特殊文件名了。

[root@localhost] ~$ find . -name 't t.txt' -type f -print0 | xargs -0 cat 
a b c d e f g   
h i j k l m n   
o p q  
r s t  
u v w x y z
原文地址:https://www.cnblogs.com/fanren224/p/8463335.html