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

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

大宇进阶之路

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值