侧边栏壁纸
  • 累计撰写 221 篇文章
  • 累计创建 205 个标签
  • 累计收到 0 条评论

目 录CONTENT

文章目录

xargs 和 exec 详解

zhanjie.me
2016-08-19 / 0 评论 / 0 点赞 / 0 阅读 / 0 字

xargs 和 exec 详解

xargs 应用

[root@localhost ~]# echo "1212121212">123.txt

[root@localhost ~]# ls 123.txt |xargs cat

1212121212

  它的作用就是把管道符前面的输出作为 xargs 后面的命令的输入。xargs 常常和 find 命令在一起使用,例如查找当前目录下创建时间大于10天的文件,然后再删除。

[root@localhost ~]# find . -mtime +10|xargs rm

  xargs 后面的 rm 也可以加选项,当是目录时,就需要 -r 选项了。

  xargs 强大的功能:

[root@localhost test]# touch 1.txt 2.txt 3.txt 4.txt 5.txt

[root@localhost test]# ls

1.txt  2.txt  3.txt  4.txt  5.txt

[root@localhost test]# ls *.txt |xargs -n1 -i{} mv {} {}_bak

[root@localhost test]# ls

1.txt_bak  2.txt_bak  3.txt_bak  4.txt_bak  5.txt_bak

  xargs -n1 -i{} 类似 for 循环, -n1意思是一个一个对象的去处理,-i{} 把前面的对象使用{}取代,mv {} {}_bak 相当于mv 1.txt 1.txt_bak 。

exec 应用

  使用 find 命令时,经常使用的一个选项就是 -exec 了,可以达到和 xargs 同样的效果。比如,查找当前目录下创建时间超过10天的文件并删除。

[root@localhost ~]# find . -mtime +10 -exec rm -rf {} \;

  这个命令中的{}也是作为前面 find 出来的文件的替代符,后面的 \ 为 ; 的脱义符,不然shell会把分号当成该行命令的结尾。

 批量更改文件名:

[root@localhost test]# find ./*_bak -exec mv {} {}_bak \;

[root@localhost test]# ls

1.txt_bak_bak  2.txt_bak_bak  3.txt_bak_bak  4.txt_bak_bak  5.txt_bak_bak
0

评论区