[root@localhost Test]# cat sh1.3.sh | grep fruit

但是,有些命令只能以命令行参数的形式接受数据,而无法通过stdin接受数据流。在这种情况下,我们没法用管道来提供那些只有通过命令行参数才能提供的数据。那就只能另辟蹊径了。该xargs命令出场了,它擅长将标准输入数据转换成命令行参数。xargs能够处理stdin并将其转换为特定命令的命令行参数。xargs也可以将单行或多行文本输入转换成其他格式,例如单行变多行或是多行变单行。
find /sbin -perm +700 |ls -l 这个命令是错误的
find /sbin -perm +700 |xargs ls -l 这样才是正确的
xargs 可以读入 stdin 的资料,并且以空白字元或断行字元作为分辨,将 stdin 的资料分隔成为 arguments 。 因为是以空白字元作为分隔,所以,如果有一些档名或者是其他意义的名词内含有空白字元的时候, xargs 可能就会误判了~他的用法其实也还满简单的!就来看一看先!
xargs命令应该紧跟在管道操作符之后,以标准输入作为主要的源数据流。它使用stdin并通过提供命令行参数来执行其他命令。
xargs命令把从stdin接收到的数据重新格式化,再将其作为参数提供给其他命令。xargs可以作为一种替代,其作用类似于find命令中的 -exec。下面是各种xargs命令的使用技巧。
1、多行输入转换成单行输出
[root@localhost Test]# cat exam.txt
#!/bin/bash
1 2 3 4 5
6 7
8
[root@localhost Test]# cat exam.txt | xargs
2、将单行输入转换成多行输出
[root@localhost Test]# vim exam.txt
[root@localhost Test]# cat exam.txt | xargs -n 3
#!/bin/bash 1 2
3 4 5
6 7 8
现在来看看xargs使用的选项参数
xargs [-0prtx] [-E eof-str] [-e[eof-str]] [--eof[=eof-str]] [--null] [-d delimiter] [--delimiter delimiter] [-I replace-str] [-i[replace-str]]
[--replace[=replace-str]] [-l[max-lines]] [-L max-lines] [--max-lines[=max-lines]] [-n max-args] [--max-args=max-args] [-s max-chars]
[--max-chars=max-chars] [-P max-procs] [--max-procs=max-procs] [--interactive] [--verbose] [--exit] [--no-run-if-empty] [--arg-file=file]
[--show-limits] [--version] [--help] [command [initial-arguments]]
-a 从文件中读入而不是标准输入中读取
[root@localhost Test]# vim test.txt
[root@localhost Test]# cat test.txt
aa bb cc dd
ee ff gg
[root@localhost Test]# xargs -a test.txt
aa bb cc dd ee ff gg
-0 当输入有特殊字符时,将其作为一般的字符处理,如有空格
[root@localhost Test]# echo "//" | xargs
//
[root@localhost Test]# echo "//" | xargs -0
-d 指定分隔符
[root@localhost Test]# cat test.txt
aa bb cc dd
ee ff gg
[root@localhost Test]# cat test.txt | xargs -d "c"
-E eof-str ,指定结束标志为eof-str
,xargs
处理到这个标志就会停止
[root@localhost Test]# cat test.txt
aa bb cc dd
ee ff gg
[root@localhost Test]# xargs -E "dd" -a test.txt
aa bb cc
[root@localhost Test]# cat test.txt | xargs -E "dd"
aa bb cc
-L max-lines: 每次读取max-line
行输入交由xargs
处理
[root@localhost Test]# cat test.txt
aa bb cc dd
ee ff gg
[root@localhost Test]# cat test.txt | xargs -L 2
aa bb cc dd ee ff gg
-l: 类似于-L
,区别在于-l
可以不指定参数,默认为1.
-n max-args: 每行执行max-args
个输入,默认执行所有
[root@localhost Test]# cat test.txt | xargs -n 2
aa bb
cc dd
ee ff
gg
-t: 先打印执行的命令,然后执行
[root@localhost Test]# cat test.txt | xargs -t
/bin/echo aa bb cc dd ee ff gg
aa bb cc dd ee ff gg
-I replace-str: 将每行输入内容替换为replace-str
[root@localhost Test]# cat test.txt | xargs -t -I {} echo {} >> test.txt
echo aa bb cc dd
echo ee ff gg