Linux xargs

产生命令的参数。常和find 在一块儿连用。bash

1. echo 'one two three' | xargs mkdirui

 

2. find /tmp -mtime +14 | xargs rmurl

 

3. time find . -type f -name "*.txt" -exec rm {} \; 0.35s user 0.11s system 99% cpu 0.467 totalspa

time find ./foo -type f -name "*.txt" | xargs rm 0.00s user 0.01s system 75% cpu 0.016 totalcode

4. echo 'one two three' | xargs -t rmthree

5. echo 'one two three' | xargs -p touch图片

6. cat foo.txt | xargs -I % sh -c 'echo %; mkdir %'字符串

 

读取stdin,将格式化后的参数传递给命令

假设一个命令为 xgj.sh 和一个保存参数的文件args.txt:get

args.txt已经具有执行权限string

[root@entel2 test]# cat xgj.sh #!/bin/bash #打印全部的参数 echo $* [root@entel2 test]# cat args.txt aaa bbb ccc
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

xargs的一个选项-I,

使用-I指定一个替换字符串{},

这个字符串在xargs扩展时会被替换掉,当-I与xargs结合使用,每个参数命令都会被执行一次:

[root@entel2 test]# cat args.txt | xargs -I {} ./xgj.sh XXX {} YYY XXX aaa YYY XXX bbb YYY XXX ccc YYY
  • 1
  • 2
  • 3
  • 4

复制全部图片文件到 /data/images 目录下:

 ls *.jpg | xargs -n1 -I cp {} /data/images 
  • 1

xargs结合find使用

用rm 删除太多的文件时候,可能获得一个错误信息: 
/bin/rm Argument list too long.

用xargs去避免这个问题:

 find . -type f -name "*.log" -print0 | xargs -0 rm -f 
  • 1

xargs -0将\0做为定界符。

-0 这个参数能够将\,空格等字符还原成通常字符。

统计一个源代码目录中全部py文件的行数:

find . -type f -name "*.py" -print0 | xargs -0 wc -l 
  • 1

查找全部的jpg 文件,而且压缩它们:

 find . -type f -name "*.jpg" -print | xargs tar -czvf images.tar.gz 
  • 1

xargs其余应用

假如你有一个文件包含了不少你但愿下载的URL,你可以使用xargs下载全部连接:

 cat url-list.txt | xargs wget -c 
相关文章
相关标签/搜索