参考地址:http://man.linuxde.net/xargs
http://www.cnblogs.com/wangqiguo/p/6464234.html
说明:xargs的默认命令是echo,空格是默认定界符。这意味着通过管道传递给xargs的输入将会包含换行和空白,不过通过xargs的处理,换行和空白将被空格取代。
xargs与管道有什么不同呢,这是两个很容易混淆的东西,看了上面的xargs的例子还是有点云里雾里的话,我们来看下面的例子弄清楚为什么需要xargs:
echo '--help' | cat
输出:
--help
echo '--help' | xargs cat
输出:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
|
Usage:
cat
[OPTION]... [FILE]...
Concatenate FILE(s), or standard input, to standard output.
-A, --show-all equivalent to -vET
-b, --number-nonblank number nonempty output lines
-e equivalent to -vE
-E, --show-ends display $ at end of each line
-n, --number number all output lines
-s, --squeeze-blank suppress repeated empty output lines
-t equivalent to -vT
-T, --show-tabs display TAB characters as ^I
-u (ignored)
-
v
, --show-nonprinting use ^ and M- notation, except
for
LFD and TAB
--help display this help and
exit
--version output version information and
exit
With no FILE, or when FILE is -,
read
standard input.
Examples:
cat
f - g Output f
's contents, then standard input, then g'
s contents.
cat
Copy standard input to standard output.
Report
cat
bugs to bug-coreutils@gnu.org
GNU coreutils home page: <http:
//www
.gnu.org
/software/coreutils/
>
General help using GNU software: <http:
//www
.gnu.org
/gethelp/
>
For complete documentation, run: info coreutils
'cat invocation'
|
可以看到 echo '--help' | cat 该命令输出的是echo的内容,也就是说将echo的内容当作cat处理的文件内容了,实际上就是echo命令的输出通过管道定向到cat的输入了。然后cat从其标准输入中读取待处理的文本内容。这等价于在test.txt文件中有一行字符 '--help' 然后运行 cat test.txt 的效果。
而 echo '--help' | xargs cat 等价于 cat --help 什么意思呢,就是xargs将其接受的字符串 --help 做成cat的一个命令参数来运行cat命令,同样 echo 'test.c test.cpp' | xargs cat 等价于 cat test.c test.cpp 此时会将test.c和test.cpp的内容都显示出来。
xargs命令用法
定义一个测试文件,内有多行文本数据:
cat test.txt
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 test.txt | xargs
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
-n选项多行输出
cat test.txt | xargs -n3
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