要回答标题中关于如何使用xargs
中间而不是结尾的输入的原始问题:
$ echo a b c | xargs -I {} echo before {} after
before a b c after
这将{}
在命令中替换为管道输出。BSD 和 GNU xargs 之间存在一些细微差别,如下所述:
BSD xargs(例如在 MacOS/Darwin、freebsd 上)
使用-I REPLACE
,它将替换REPLACE
命令中的字符串(或您传递的任何内容)。例如:
$ echo a b c | xargs -I {} echo before {} after
before a b c after
$ echo a b c | xargs -I REPLACE echo before REPLACE after
before a b c after
$ echo 'a
> b
> c' | xargs -L1 -I {} echo before {} after
before a after
before b after
before c after
手册页描述了该选项:
-I replstr
Execute utility for each input line, replacing one or more occur-
rences of replstr in up to replacements (or 5 if no -R flag is
specified) arguments to utility with the entire line of input.
The resulting arguments, after replacement is done, will not be
allowed to grow beyond replsize (or 255 if no -S flag is speci-
fied) bytes; this is implemented by concatenating as much of the
argument containing replstr as possible, to the constructed argu-
ments to utility, up to replsize bytes. The size limit does not
apply to arguments to utility which do not contain replstr, and
furthermore, no replacement will be done on utility itself.
Implies -x.
GNU xargs(例如在 Linux 上)
$ echo a b c | xargs -i echo before {} after
before a b c after
$ echo a b c | xargs -I THING echo before THING after
before a b c after
使用手册页描述的 the-I REPLACE
或 the-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.
-i[replace-str], --replace[=replace-str]
This option is a synonym for -Ireplace-str if replace-str is
specified. If the replace-str argument is missing, the effect
is the same as -I{}. This option is deprecated; use -I
instead.
-L 1
on-I
表示它将在单独的命令中执行每个输入:
$ echo "a
> b
> c" | xargs -I THING echo before THING after
before a after
before b after
before c after
(-i
没有这种效果,但显然已被弃用。)