美文网首页
xargs 2022-08-03

xargs 2022-08-03

作者: 9_SooHyun | 来源:发表于2022-08-03 15:12 被阅读0次

    The xargs command is used in a UNIX shell to convert input from standard input into arguments to a command.
    xargs命令实际上就是将所有空格、制表符和分行符都替换为空格并【压缩到一行上显示】,这一整行将作为一个字符串传入到目标命令中,而它支持的option决定了将stdin传来的结果转化成不同的字符串的方式,如处理分隔符的问题、转化成多个字符串分批执行的问题

    common usage:
    command1 | xargs command2

    - uses a single command after the piped operation

    eg.ls | xargs ls

    - run multiple commands along with xargs.

    eg.
    # echo "file1 file2 file3" | xargs -t -I % sh -c '{ touch %; ls -l %; }'

    - 常用的option
    • -I replace-str
      Replace occurrences of replace-str in the initial-arguments with names read from standard input. Also, unquoted blanks do not terminate input items; instead the separator is the newline character. Implies -x and -L 1.
      eg.

      $ ls | xargs -p -I % sh -c 'echo %; ls -l %'
      sh -c echo files; ls -l files?...
      

      ls | xargs -p -I % sh -c 'echo %; ls -l %' %符号都被替换成ls的xargs结果,因此等价于sh -c echo files; ls -l files

    • -0
      使用null character分割输入并且不做任何转义
      Input items are terminated by a null character instead of by whitespace, and the quotes and backslash are not special (every character is taken literally,所有字符都是字面义而不会转义). Disables the end of file string, which is treated like any other argument. Useful when input items might contain white space, quote marks, or backslashes.
      The GNU find -print0 option produces input suitable for this mode. eg find . -print0 | xargs -0 echo

      man find可以看到find命令支持一个expression叫-print0,它的输出就是以null character分隔各个item

      -print0
      True; print the full file name on the standard output, followed by a null character (instead of the newline character that -print uses).
      This allows file names that contain newlines or other types of white space to be correctly interpreted by programs that process the find output. This option corresponds to the -0 option of xargs.

    相关文章

      网友评论

          本文标题:xargs 2022-08-03

          本文链接:https://www.haomeiwen.com/subject/hdoswrtx.html