Fixed last argument with xargs

Is it possible to use xargs to invoke a command so that the last argument of the command is fixed?

My attempt:

printf '%sn' a b c d | xargs -I{} echo {} LAST

ends up doing

echo a LAST  
echo b LAST  
echo c LAST  
echo d LAST

I want for xargs to invoke

echo a b c d LAST
#fit as many as you can but always finish wiht LAST

Is this possible to do, preferably in a portable way?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

tl;dr; this is how you could do it portably, without -I and other broken fancy options:

$ echo a b c d f g | xargs -n 2 sh -c 'echo "<a href="https://getridbug.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="103450">[email protected]</a>" LAST' sh
a b LAST
c d LAST
f g LAST

$ seq 1 100000 | xargs sh -c 'echo "$#" LAST' sh
23692 LAST
21841 LAST
21841 LAST
21841 LAST
10785 LAST

The problem with the -I option is that it’s broken by design, and there is no way around it:

$ echo a b c d f g | xargs -I {} -n 1 echo {} LAST
a b c d f g LAST
$ echo a b c d f g | xargs -I {} -n 2 echo {} LAST
{} LAST a b
{} LAST c d
{} LAST f g

But they’re probably covered, because that’s what the standard says:

-I replstr
^[XSI] [Option Start] Insert mode: utility is executed for each
line from standard input
, taking the entire line as a single
argument
, inserting it in arguments for each occurrence of
replstr.

And it doesn’t say anything about the interaction with the -n and -d options, so they’re free to do whatever they please.

This is how it is on an (older) FreeBSD, less unexpected but non-standard:

fzu$ echo a b c d f g | xargs -I {} -n 2 echo {} LAST
a b LAST
c d LAST
f g LAST
fzu$ echo a b c d f g | xargs -I {} -n 1 echo {} LAST
a LAST
b LAST
c LAST
d LAST
f LAST
g LAST

Method 2

Not with xargs (alone). If you have an item list of unpredictable length, how should xargs know from the beginning (= first element) which element would be the last one?
You’ll need some additional logics around it to separate the desired element from the others.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x