Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to perform the reverse of `xargs`?

Tags:

linux

bash

unix

I have a list of numbers that I want to reverse.

They are already sorted.

35 53 102 342

I want this:

342 102 53 35

So I thought of this:

echo $NUMBERS | ??? | tac | xargs

What's the ???

It should turn a space separated list into a line separated list.

I'd like to avoid having to set IFS.

Maybe I can use bash arrays, but I was hoping there's a command whose purpose in life is to do the opposite of xargs (maybe xargs is more than a one trick pony as well!!)

like image 762
Steven Lu Avatar asked Aug 09 '13 15:08

Steven Lu


People also ask

How do you stop xargs?

From man xargs : If any invocation of the command exits with a status of 255, xargs will stop immediately without reading any further input.

How do you pass arguments to xargs?

The -c flag to sh only accepts one argument while xargs is splitting the arguments on whitespace - that's why the double quoting works (one level to make it a single word for the shell, one for xargs).

What xargs means?

xargs (short for "extended arguments") is a command on Unix and most Unix-like operating systems used to build and execute commands from standard input. It converts input from standard input into arguments to a command.


2 Answers

You can use printf for that. For example:

$ printf "%s\n" 35 53 102 342
35
53
102
342
$ printf "%s\n" 35 53 102 342|tac
342
102
53
35
like image 157
Mat Avatar answered Sep 20 '22 19:09

Mat


Another answer (easy to remember but not as fast as the printf method):

$ xargs -n 1 echo

e.g.

$ NUMBERS="35 53 102 342"
$ echo $NUMBERS | xargs -n 1 echo | tac | xargs
342 102 53 35

Here is the xargs manual for -n option:

-n number
         Set the maximum number of arguments taken from standard input for 
         each invocation of utility.  An invocation of utility will use less 
         than number standard input arguments if the number of bytes accumu-
         lated (see the -s option) exceeds the specified size or there are 
         fewer than number arguments remaining for the last invocation of 
         utility.  The current default value for number is 5000.
like image 24
baggzy Avatar answered Sep 21 '22 19:09

baggzy