linux xargs命令

摘自:man xargs

DESCRIPTION

       This manual page documents the GNU version of xargs.  xargs 
       put,  delimited  by blanks (which can be protected with double or single quotes or a backslash)
       or newlines, and executes the command (default is /bin/echo) one or more times  with  any  ini‐
       tial-arguments  followed  by items read from standard input.  Blank lines on the standard input
       are ignored.

       Because Unix filenames can contain blanks and newlines, this default behaviour is  often  prob‐
       lematic;  filenames  containing  blanks and/or newlines are incorrectly processed by xargs.  In
       these situations it is better to use the -0 option, which prevents such problems.   When  using
       this  option  you  will need to ensure that the program which produces the input for xargs also
       uses a null character as a separator.  If that program is GNU find for example, the -print0 op‐
       tion does this for you.

       If  any invocation of the command exits with a status of 255, xargs will stop immediately with‐
       out reading any further input.  An error message is issued on stderr when this happens.

  

  xargs是给命令传递参数的一个过滤器,用于组合多个命令时非常好用,常通过管道连接多个命令,将前一个命令的输出传递给下一条命令作为输入。默认情况下以空格或换行来分割参数,当时由于Unix文件名中可以包含空格和换行,所以用xargs处理类似的参数时肯定会出错。一般会这样使用,利用-0参数,该参数表示以null来分割参数,当使用该参数时就必须保证前一条命令的输出是以null分割的。以find命令为例,find命令中的-print0参数就是多个输出结果的以null分隔(默认是以换行分隔,即默认采用-print参数)。一旦xargs某次执行返回状态255,则xargs会中止不再继续处理剩余的输入参数,并输出错误信息。


  xargs常与find命令联合使用,下面看几个例子:

下面的例子在整个系统中查找内存信息转储文件(core dump) ,然后把结果保存到/tmp/core.log 文件中: 

$ find . -name "core" -print | xargs echo "" >/tmp/core.log 

下面的例子在/apps/audit目录下查找所有用户具有读、写和执行权限的文件,并收回相应的写权限: 

$ find /apps/audit -perm -7 -print | xargs chmod o-w 

下面的例子中,我们用grep命令在所有的普通文件中搜索device这个词: 

$ find / -type f -print | xargs grep "device" 

查找所有的jpg 文件,并且压缩它:

$ find / -name *.jpg -type f -print | xargs tar -cvzf images.tar.gz

以上例子都是没有使用-0参数的,所以会有遇到含有空格的文件名的危险,下面看一个使用-0参数的例子。

查找并删除文件:

find ~ -name ‘*.log’ -print0 | xargs -0 rm -f


另外:

  xargs命令不仅仅能读取前面命令的输出,也能从标准输入或者文件读取内容进行处理。

  xargs命令不仅仅用于与find命令连接,其他命令都可以通过管道进行链接。

  其他更多的使用方法请查看相关文档或资料。


  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值