xargs是给命令传递参数的一个过滤器,也是组合多个命令的一个工具。它把一个数据流分割为一些足够小的块,以方便过滤器和命令进行处理。一般状况下,xargs从管道或者stdin中读取数据,可是它也可以从文件的输出中读取数据。xargs的默认命令是echo,这意味着经过管道传递给xargs的输入将会包含换行和空白,不过经过xargs的处理,换行和空白将被空格取代。 xargs 是一个强有力的命令,它可以捕获一个命令的输出,而后传递给另一个命令,下面是一些如何有效使用xargs 的实用例子。工具
当你尝试用rm 删除太多的文件,你可能获得一个错误信息:/bin/rm Argument list too long. 用xargs 去避免这个问题flex
find ~ -name ‘*.log’ -print0 | xargs -0 rm -f
得到/etc/ 下全部*.conf 结尾的文件列表,有几种不一样的方法能获得相同的结果,下面的例子仅仅是示范怎么实用xargs ,在这个例子中实用 xargs将find 命令的输出传递给ls -lthis
# find /etc -name "*.conf" | xargs ls –l
假如你有一个文件包含了不少你但愿下载的URL, 你可以使用xargs 下载全部连接url
# cat url-list.txt | xargs wget –c
查找全部的jpg 文件,而且压缩它spa
# find / -name *.jpg -type f -print | xargs tar -cvzf images.tar.gz
拷贝全部的图片文件到一个外部的硬盘驱动code
# ls *.jpg | xargs -n1 -i cp {} /external-hard-drive/directory
EXAMPLES图片
find /tmp -name core -type f -print | xargs /bin/rm -f
Find files named core in or below the directory /tmp and delete them. Note that this will work incorrectly if there are any filenames containing newlines or spaces.ci
find /tmp -name core -type f -print0 | xargs -0 /bin/rm -f
Find files named core in or below the directory /tmp and delete them, processing filenames in such a way that file or directory names containing spaces or newlines are correctly handled.get
find /tmp -depth -name core -type f -delete
Find files named core in or below the directory /tmp and delete them, but more efficiently than in the previous example (because we avoid the need to use fork(2) and exec(2) to launch rm and we don't need the extra xargs process).input
cut -d: -f1 < /etc/passwd | sort | xargs echo
Generates a compact listing of all the users on the system.
xargs sh -c 'emacs "$@" < /dev/tty' emacs
Launches the minimum number of copies of Emacs needed, one after the other, to edit the files listed on xargs' standard input. This example achieves the same effect as BSD's -o option, but in a more flexible and portable way.