Xargs用法详解
1. 简介:
之所以能用到这个命令,关键是由于很多命令不支持|管道
来传递参数,而日常工作中有有这个必要,所以就有了xargs
命令,例如:
find /sbin -perm +700 |ls -l 这个命令是错误的
find /sbin -perm +700 |xargs ls -l 这样才是正确的
xargs 可以读入 stdin 的资料,并且以空白字元或断行字元作为分辨,将 stdin 的资料分隔成为 arguments 。
2. 选项解释:
- -0:当sdtin含有特殊字符的时候,将其当成一般字符,例如:
root@localhost:~/test#echo "//"|xargs echo
root@localhost:~/test#echo "//"|xargs -0 echo
- -a <file>:从文件中读入作为参数。例如:
root@localhost:~/test#cat test
#!/bin/sh
echo "hello world/n"
root@localhost:~/test#xargs -a test echo
#!/bin/sh echo hello world/n
- -e <flag:注意有的时候可能会是-E,flag必须是一个以空格分隔的标志,当xargs分析到含有flag这个标志的时候就停止。例如:
root@localhost:~/test#cat txt
/bin tao shou kun
root@localhost:~/test#cat txt|xargs -E 'shou' echo
/bin tao
- -p: 当每次执行一个argument的时候询问一次用户。例如:
root@localhost:~/test#cat txt|xargs -p echo
echo /bin tao shou kun ff ?...y
/bin tao shou kun ff
- -n <num>:表示命令在执行的时候一次用的argument的个数,默认是用所有的。例如:
root@localhost:~/test#cat txt|xargs -n1 echo
/bin
tao
shou
kun
root@localhost:~/test3#cat txt|xargs echo
/bin tao shou kun
- -t:表示先打印命令,然后再执行。例如:
root@localhost:~/test#cat txt|xargs -t echo
echo /bin tao shou kun
/bin tao shou kun
- -i 或者是-I:这得看linux支持了,将xargs的每项名称,一般是一行一行赋值给{},可以用{}代替。例如:
$ ls | xargs -t -i mv {} {}.bak
- -r:
no-run-if-empty
,当xargs的输入为空的时候则停止xargs,不用再去执行了。例如:
root@localhost:~/test#echo ""|xargs -t mv
mv
mv: missing file operand
Try `mv --help' for more information.
root@localhost:~/test#echo ""|xargs -t -r mv
root@localhost:~/test#
(直接退出)