Problem using xargs --max-args --replace with default delimiter

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 give xargs arguments on separate lines:

$ printf '%s\n' a b c | xargs --max-args=1 --replace="{}" echo x "{}" y
x a y
x b y
x c y

Using POSIX options:

printf '%s\n' a b c | xargs -n 1 -I "{}" echo x "{}" y

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:

$ printf '%s\n' a b c | xargs -I "{}" echo x "{}" y
x a y
x b y
x c y

In fact, the Rationale section of the POSIX spec on xargs says (my emphasis)

The -I, -L, and -n options are mutually-exclusive. Some implementations use the last one specified if more than one is given on a command line; other implementations treat combinations of the options in different ways.

While testing this, I noticed that OpenBSD's version of xargs will do the the following if -n and -I are used together:

$ echo  a b c | xargs -n 1  -I "{}" echo x "{}" y
x a y
x b y
x c y

This is different from what GNU coreutils' xargs does (which produces x 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).

Tags:

Linux

Xargs

Gnu