xargs -I 行为

Mec*_*MK1 2 bash xargs

一个变量var包含多个参数,每个参数由一个新行分隔。

echo "$var" | xargs -I % echo ABC %
#Results in:
#ABC One
#ABC Two
#ABC Three
Run Code Online (Sandbox Code Playgroud)

但是,当省略-I%字符时,我得到以下信息:

echo "$var" | xargs echo ABC
#Results in:
#ABC One Two Three
Run Code Online (Sandbox Code Playgroud)

我曾经读过 {} 将替代当前参数(就像 find 一样),但这不会发生。我究竟做错了什么?

Nic*_*ton 5

通常的行为xargs是将尽可能多的参数粘贴到它运行的任何命令的命令行上,迭代'直到它全部完成。以这种方式使用时,它是解决命令行长度限制问题的方法。

但是,当您指定该-I选项时,它会针对每个参数单独运行命令,一次一个。我认为这在 Linuxxargs -I选项的文档中并不完全明显,但这就是它们的意思。

-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.
Run Code Online (Sandbox Code Playgroud)

  • `此外,未加引号的空格不会终止输入项;相反,分隔符是换行符。`——这是理解行为的核心。如果没有 `-I`,`xargs` 只会将输入视为单个字段,因为换行符不是字段分隔符。使用`-I`,突然换行_is_一个字段分隔符,因此`xargs`看到三个字段(它迭代)。这是一个真正的微妙点,但在引用的“手册”页中进行了解释。 (2认同)