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!!)
From man xargs : If any invocation of the command exits with a status of 255, xargs will stop immediately without reading any further input.
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).
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.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With