纸上得来终觉浅,绝知此事要躬行。

Unix
命令都带有参数,有些命令可以接受”标准输入(stdin
)”作为参数。而**管道命令(|
)**的作用,是将左侧命令的标准输出转换为标准输入,提供给右侧命令作为参数使用。虽然,在 Unix
系统中大多数命令都不接受标准输入作为参数,只能直接在命令行输入参数,这导致无法用管道命令传递参数。比如,我们日常使用的 echo
命令就不接受管道传参。而 xargs
命令的作用,就是将标准输入转为命令行参数。
$ cat /etc/passwd | grep root
$ echo "hello world" | echo
$ echo "hello world" | xargs echo
hello world
- 需要注意的是
xargs
后面的默认跟的是 echo
命令,所以它可以单独使用。
$ xargs
hello
hello
$ xargs find -name
"*.txt"
./foo.txt
./hello.txt
编号 |
参数 |
作用 |
1 |
-d |
指定分隔符,默认使用空格分割 |
$ echo "one two three" | xargs mkdir
$ echo -e "a\tb\tc" | xargs -d "\t" echo
a b c
编号 |
参数 |
作用 |
2 |
-p |
打印出要执行的命令并询问用户是否要执行 |
2 |
-t |
打印出要执行的命令并不询问用户是否要执行 |
$ echo 'one two three' | xargs -p touch
touch one two three ?...
$ echo 'one two three' | xargs -t rm
rm one two three
编号 |
参数 |
作用 |
3 |
-0 |
表示用 null 当作分隔符 |
$ find /path -type f -print0 | xargs -0 rm
$ find . -name "*.txt" | xargs grep "abc"
编号 |
参数 |
作用 |
4 |
-L |
指定多少行作为一个命令行参数 |
$ xargs -L 1 find -name
"*.txt"
./foo.txt
./hello.txt
"*.md"
./README.md
$ echo -e "a\nb\nc" | xargs -L 1 echo
a
b
c
编号 |
参数 |
作用 |
5 |
-n |
指定每次将多少项作为命令行参数 |
$ echo {0..9} | xargs -n 2 echo
0 1
2 3
4 5
6 7
8 9
编号 |
参数 |
作用 |
6 |
-I |
指定每一项命令行参数的替代字符串 |
$ cat foo.txt
one
two
three
$ cat foo.txt | xargs -I file sh -c 'echo file; mkdir file'
one
two
three
$ ls
one two three
编号 |
参数 |
作用 |
7 |
--max-procs |
同时用多少个进程并行执行命令 |
$ docker ps -q | xargs -n 1 --max-procs 0 docker kill