Linux中xargs的使用
xargs(英文全拼: eXtended ARGuments)是给命令传递参数的一个过滤器,也是组合多个命令的一个工具。
xargs 可以将管道或标准输入(stdin)数据转换成命令行参数,也能够从文件的输出中读取数据。
xargs 也可以将单行或多行文本输入转换为其他格式,例如多行变单行,单行变多行。
xargs 默认的命令是 echo,这意味着通过管道传递给 xargs 的输入将会包含换行和空白,不过通过 xargs 的处理,换行和空白将被空格取代。
1.多行变单行
[root@VM-24-9-centos abc]# cat test.txt
12 1234
344
43[root@VM-24-9-centos abc]# cat test.txt |xargs
12 1234 344 43
xargs默认命令是echo
2.批量删除或者杀进程
如果有多个tomcat或者java要都停止掉;或者find多个文件要删除,可以配合使用xargs
批量创建文件或文件夹:
[root@VM-24-9-centos abc]# echo test1.txt test2.txt test3.txt |xargs touch
[root@VM-24-9-centos abc]# ll
total 0
-rw-r--r-- 1 root root 0 Apr 13 11:29 test1.txt
-rw-r--r-- 1 root root 0 Apr 13 11:29 test2.txt
-rw-r--r-- 1 root root 0 Apr 13 11:29 test3.txt
-rw-r--r-- 1 root root 0 Apr 13 11:25 test 4.txt
删多个txt文件:
[root@VM-24-9-centos abc]# find /root/aaa/abc -name '*.txt'
/root/aaa/abc/test3.txt
/root/aaa/abc/test.txt
/root/aaa/abc/test 4.txt
/root/aaa/abc/test2.txt
[root@VM-24-9-centos abc]# find /root/aaa/abc -name '*.txt'|xargs rm
rm: cannot remove ‘/root/aaa/abc/test’: No such file or directory
rm: cannot remove ‘4.txt’: No such file or directory
[root@VM-24-9-centos abc]# ll
total 0
-rw-r--r-- 1 root root 0 Apr 13 11:25 test 4.txt
[root@VM-24-9-centos abc]
一共有4个txt文件,但是“test 4.txt”这个文件名带有空格,xargs默认以空格、Tab制表符、回车符
为分隔符和结束符,当有的文件本身包含空格时,就会出问题
针对该问题,find提供了一个print0
选项,设置find在输出文件名后自动添加一个NULL
来替代换行符,而xargs -0表示xargs用NULL来作为分隔符。
[root@VM-24-9-centos abc]# ll
total 0
-rw-r--r-- 1 root root 0 Apr 13 11:29 test1.txt
-rw-r--r-- 1 root root 0 Apr 13 11:29 test2.txt
-rw-r--r-- 1 root root 0 Apr 13 11:37 test3.txt
-rw-r--r-- 1 root root 0 Apr 13 11:25 test 4.txt
[root@VM-24-9-centos abc]# find /root/aaa/abc -name '*.txt' -print0 | xargs -0 rm
[root@VM-24-9-centos abc]# ll
total 0
删除多个进程:
ps -ef | grep tomcat | grep -v grep| awk '{print $2}'|xargs kill -9
3. 将xargs的每项名称,一般是一行一行赋值给{},可以用{}代替
比如查找出文件后复制到 其他目录
find ./ -name "*.txt" |xargs -i cp {} /root/aaa