1.xargs命令的使用方法
将前一个命令的标准输出传递给下一个命令,作为它的参数,xargs默认的命令是echo, 空格是默认的定界符;
将多行输入转换为单行;
注意:处理特殊文件名需要采用-0来避免特殊字符(xargs -0)
[root@osker /]# find /root/ -type f -name '*.txt' | xargs
/root/1.txt /root/2.txt /root/3.txt
[root@osker /]# find /root/ -type f -name '*.txt' | xargs echo start
start /root/1.txt /root/2.txt /root/3.txt
###-i:逐项处理,默认以空格为分隔符;{}表示前面传过来的结果。
[root@osker /]# find /root/ -type f -name '*.txt' | xargs -i mv {} {}.bak
[root@osker /]# ll /root/
total 0
-rw-r--r--. 1 root root 0 Apr 16 21:35 1.txt.bak
-rw-r--r--. 1 root root 0 Apr 16 21:35 2.txt.bak
-rw-r--r--. 1 root root 0 Apr 16 21:35 3.txt.bak
###-n: 指定一次处理的参数个数
[root@osker /]# find /root/ -type f -name '*.bak' | xargs -n 2
/root/1.txt.bak /root/2.txt.bak
/root/3.txt.bak
###统计当前目录中每个文件有多少行?
ls | xargs -i wc -l {}
80 a.txt
100 b.txt
- exec的用法
exec的参数时一个一个传递的,传递一个参数执行一次命令;
-exec {} ;
{}表示命令的参数;以;表示命令的结束,\是转义符,因为分号在命令中还有其他用途,所有就用一个\来限定表示这是一个分号,而不是其他意思;
-ok和-exec的左右相同,格式也相同,只不多是一种更安全的模式来执行该参数,在执行每个命令之前都会给一次提示,让用户来确定是否执行。
[root@osker /]# find /root/ -type f -name '*.bak' -ok echo start {} \;
< echo ... /root/1.txt.bak > ? y
start /root/1.txt.bak
< echo ... /root/2.txt.bak > ? y
start /root/2.txt.bak
< echo ... /root/3.txt.bak > ? y
start /root/3.txt.bak
[root@osker /]# find /root/ -type f -name '*.txt' -exec echo start {} \;
start /root/1.txt
start /root/2.txt
start /root/3.txt
###统计当前目录中每个文件有多少行?
find . -name "*.txt" -exec wc -l {} \;
20 ./a.txt
180 ./b.txt
###这个地方用ls,ls后面的参数容易当成ls的参数
3.两个命令效率的比较
[root@nfs ~]# touch {1..10000}.txt
[root@nfs ~]# time find ./ -type f -name '*.txt' |xargs rm -f
real 0m0.203s
user 0m0.016s
sys 0m0.186s
[root@nfs ~]# touch {1..10000}.txt
[root@nfs ~]# time find ./ -type f -name '*.txt' -exec rm {} \;
real 0m8.074s
user 0m3.717s
sys 0m4.294s
从以上可以看出xargs命令的执行下效率比exec要高。