This works as expected:
$ echo a b c | xargs --replace="{}" echo x "{}" y
x a b c y
This does too:
$ echo a b c | xargs --max-args=1 echo x
x a
x b
x c
But this doesn't work as expected:
$ echo a b c | xargs --max-args=1 --replace="{}" echo x "{}" y
x a b c y
And neither does this:
$ echo a b c | xargs --delimiter=' ' --max-args=1 --replace="{}" echo x "{}" y
x a y
x b y
x c
y
I expected this output:
x a y
x b y
x c y
As a workaround, I am using printf and two xargs, but that is ugly:
$ echo a b c | xargs printf '%s\0' | \
> xargs --null --max-args=1 --replace="{}" echo x "{}" y
x a y
x b y
x c y
Any idea why this is happening?
Best Answer
According to the POSIX documentation,
xargs
should run the given utility with arguments delimited by either spaces or newlines, and this is what happens in the two first examples of yours.However, when
--replace
(or-I
) is used, only newlines will delimit arguments. The remedy is to givexargs
arguments on separate lines:Using POSIX options:
Here, I give
xargs
not one line but three. It takes one line (at most) and executes the utility with that as the argument.Note also that
-n 1
(or--max-args=1
) in the above is not needed as it's the number of replacements made by-I
that determines the number of arguments used:In fact, the Rationale section of the POSIX spec on
xargs
says (my emphasis)While testing this, I noticed that OpenBSD's version of
xargs
will do the the following if-n
and-I
are used together:This is different from what GNU coreutils'
xargs
does (which producesx a b c y
). This is due to the implementation accepting spaces as argument delimiter with-n
, even though-I
is used. So, don't use-I
and-n
together (it's not needed anyway).