Linux xargs命令
xargs是给命令传递参数的一个过滤器,也是组合多个命令的一个工具。它把一个数据流分割为一些足够小的块,以方便过滤器和命令进行处理。通常情况下,xargs从管道或者stdin中读取数据,但是它也能够从文件的输出中读取数据。xargs的默认命令是echo,这意味着通过管道传递给xargs的输入将会包含换行和空白,不过通过xargs的处理,换行和空白将被空格取代。
xargs 是一个强有力的命令,它能够捕获一个命令的输出,然后传递给另外一个命令,下面是一些如何有效使用xargs 的实用例子。
1. 当你尝试用rm 删除太多的文件,你可能得到一个错误信息:/bin/rm Argument list too long. 用xargs 去避免这个问题
find ~ -name ‘*.log’ -print0 | xargs -0 rm -f
2. 获得/etc/ 下所有*.conf 结尾的文件列表,有几种不同的方法能得到相同的结果,下面的例子仅仅是示范怎么实用xargs ,在这个例子中实用 xargs将find 命令的输出传递给ls -l
# find /etc -name “*.conf” | xargs ls –l
3. 假如你有一个文件包含了很多你希望下载的URL, 你能够使用xargs 下载所有链接
# cat url-list.txt | xargs wget –c
4. 查找所有的jpg 文件,并且压缩它
# find / -name *.jpg -type f -print | xargs tar -cvzf images.tar.gz
5. 拷贝所有的图片文件到一个外部的硬盘驱动
# ls *.jpg | xargs -n1 -i cp {} /external-hard-drive/directory
关于管道符与xargs的区别!
管道是实现“将前面的标准输出作为后面的标准输入”
xargs是实现“将标准输入作为命令的参数”
一个实在的例子:
echo “–help”|cat
echo “–help”|xargs cat
如果你直接在命令行输入cat而不输入其余的任何东西,这时候的cat会等待标准输入,因此你这时候可以
通过键盘输入并按回车来让cat读取输入,cat会原样返回。而如果你输入–help,那么cat程序会在标准输出上
打印自己的帮助文档。也就是说,管道符 | 所传递给程序的不是你简单地在程序名后面输入的参数,它们会被
程序内部的读取功能如scanf和gets等接收,而xargs则是将内容作为普通的参数传递给程序,相当于你手写了
cat –help
=============================xargs的i参数==================================
find . -type f -name “*.txt” | xargs -i cp {} /tmp/k/
find . -type f -name “*.txt” | xargs -I {} cp {} /tmp/n/
加 -I 参数 需要事先指定替换字符
=============================xargs定制输出功能==================================
xargs除了可以用来传递单行命令的参数外,还可以用来格式化输出, 例如多行变单行,单行变多行。xargs的默认命令是echo,默认定界符是空格,通过管道符传递给xargs命令的多行标准输入都会变成由空格隔开的一行。例如:
1 2 3 4 5 6 7 8 9 10 | [admin@ logs]$ cat /tmp/tmp.txt /data/logs/log2016100723/api.4399sy.com.log /data/logs/api.4399sy.com.log /data/logs/log2016100823/api.4399sy.com.log /data/logs/log2016100923/api.4399sy.com.log [admin@ logs]$ cat /tmp/tmp.txt |xargs /data/logs/log2016100723/api.4399sy.com.log /data/logs/api.4399sy.com.log /data/logs/log2016100823/api.4399sy.com.log /data/logs/log2016100923/api.4399sy.com.log [admin@ logs]$ cat /tmp/tmp.txt |xargs -n2 /data/logs/log2016100723/api.4399sy.com.log /data/logs/api.4399sy.com.log /data/logs/log2016100823/api.4399sy.com.log /data/logs/log2016100923/api.4399sy.com.log |
-n参数可以用来定制输出多少行,结合cut等命令很方便做统计,-d可以用来定制定界符,可以用来删除某些字符。
stat命令,比ls查看更多的文件信息 MySQL导入.sql文件及常用命令