[关闭]
@maorongrong 2015-09-13T13:25:49.000000Z 字数 2174 阅读 580

[转载]关于xargs命令

Linux


原文--Xargs用法详解

简介

之所以能用到这个命令,关键是由于很多命令不支持|管道来传递参数,而日常工作中有有这个必要,所以就有了xargs命令,例如:

  1. find /sbin -perm +700 |ls -l 这个命令是错误的
  2. find /sbin -perm +700 |xargs ls -l 这样才是正确的

xargs 可以读入 stdin 的资料,并且以空白字元或断行字元作为分辨,将 stdin 的资料分隔成为 arguments 。 因为是以空白字元作为分隔,所以,如果有一些档名或者是其他意义的名词内含有空白字元的时候, xargs 可能就会误判了~他的用法其实也还满简单的!就来看一看先!

选项解释

-0 当sdtin含有特殊字元时候,将其当成一般字符,想/'空格等

  1. 例如:root@localhost:~/test#echo "//"|xargs echo
  2. root@localhost:~/test#echo "//"|xargs -0 echo
  3. /

-a file 从文件中读入作为sdtin,(看例一)
-e flag ,注意有的时候可能会是-E,flag必须是一个以空格分隔的标志,当xargs分析到含有flag这个标志的时候就停止。(例二)
-p 当每次执行一个argument的时候询问一次用户。(例三)
-n num 后面加次数,表示命令在执行的时候一次用的argument的个数,默认是用所有的。(例四)
-t 表示先打印命令,然后再执行。(例五)
-i 或者是-I,这得看linux支持了,将xargs的每项名称,一般是一行一行赋值给{},可以用{}代替。(例六)
-r no-run-if-empty 当xargs的输入为空的时候则停止xargs,不用再去执行了。(例七)
-s num 命令行的最好字符数,指的是xargs后面那个命令的最大命令行字符数。(例八)
-L num Use at most max-lines nonblank input lines per command line.-s是含有空格的。
-l 同-L
-d delim 分隔符,默认的xargs分隔符是回车,argument的分隔符是空格,这里修改的是xargs的分隔符(例九)
-x exit的意思,主要是配合-s使用。
-P 修改最大的进程数,默认是1,为0时候为as many as it can ,这个例子我没有想到,应该平时都用不到的吧。

应用举例

例一:

  1. root@localhost:~/test#cat test
  2. #!/bin/sh
  3. echo "hello world/n"
  4. root@localhost:~/test#xargs -a test echo
  5. #!/bin/sh echo hello world/n
  6. root@localhost:~/test#

例二:

  1. root@localhost:~/test#cat txt
  2. /bin tao shou kun
  3. root@localhost:~/test#cat txt|xargs -E 'shou' echo
  4. /bin tao
  5. root@localhost:~/test#

例三:

  1. root@localhost:~/test#cat txt|xargs -p echo
  2. echo /bin tao shou kun ff ?...y
  3. /bin tao shou kun ff

例四:

  1. root@localhost:~/test#cat txt|xargs -n1 echo
  2. /bin
  3. tao
  4. shou
  5. kun
  6. root@localhost:~/test3#cat txt|xargs echo
  7. /bin tao shou kun

例五:

  1. root@localhost:~/test#cat txt|xargs -t echo
  2. echo /bin tao shou kun
  3. /bin tao shou kun

例六:
$ ls | xargs -t -i mv {} {}.bak
例七:

  1. root@localhost:~/test#echo ""|xargs -t mv
  2. mv
  3. mv: missing file operand
  4. Try `mv --help' for more information.
  5. root@localhost:~/test#echo ""|xargs -t -r mv
  6. root@localhost:~/test#
  7. (直接退出)

例八:

  1. root@localhost:~/test#cat test |xargs -i -x -s 14 echo "{}"
  2. exp1
  3. exp5
  4. file
  5. xargs: argument line too long
  6. linux-2
  7. root@localhost:~/test#

例九:

  1. root@localhost:~/test#cat txt |xargs -i -p echo {}
  2. echo /bin tao shou kun ?...y
  3. root@localhost:~/test#cat txt |xargs -i -p -d " " echo {}
  4. echo /bin ?...y
  5. echo tao ?.../bin
  6. y
  7. echo shou ?...tao
  8. 再如:
  9. root@localhost:~/test#cat test |xargs -i -p -d " " echo {}
  10. echo exp1
  11. exp5
  12. file
  13. linux-2
  14. ngis_post
  15. tao
  16. test
  17. txt
  18. xen-3
  19. ?...y
  20. root@localhost:~/test#cat test |xargs -i -p echo {}
  21. echo exp1 ?...y
  22. echo exp5 ?...exp1
  23. y
  24. echo file ?...exp5
  25. y
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注