I have iterate over numbers in various order. I am able to display them in increasing order, even with steps like:
$ seq --separator="," 1 10 1,2,3,4,5,6,7,8,9,10 $ seq --separator="," 1 2 10 1,3,5,7,9
I am also able to display them in reverse order, neither continuous nor step wise.
$ seq --separator="," 10 1 $ seq --separator="," 10 2 1
No output for above commands.
My shell details:
$ bash --version GNU bash, version 3.2.25(1)-release (x86_64-redhat-linux-gnu) Copyright (C) 2005 Free Software Foundation, Inc.
Let me know how I would be able to display the numbers in descending order?
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
use negative increment
seq -s, 10 -2 1 10,8,6,4,2
Method 2
In general, you don’t want to use seq, it’s not portable (even among standard Linux environments). If you’re using ksh, zsh, or bash4+, you can use brace expansion:
echo {10..1..2} | tr " " ,
10,8,6,4,2
Method 3
Another way in pure bash, ksh or zsh:
for ((i=10;i>0;i-=2)) ; do echo -n "$i," ; done
A pure POSIX sh way:
i=10 while [ "$i" -gt 2 ]; do printf "$i,"; i=$((i-2)); done echo "$i"
Method 4
Now, standard POSIX ones:
awk 'BEGIN{for (i = 10; i > 0; i -= 2) print i}' | paste -sd , -
(interestingly, with mawk (and to a lesser extent gawk as well) a lot faster than GNU seq for i = 10000000 instead of i = 10)
Or
i=10; set -- while [ "$i" -gt 0 ]; do set -- "<a href="https://getridbug.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="cbef8b">[email protected]</a>" "$i" i=$(($i - 2)) done IFS=, echo "$*"
(would only be more efficient with small numbers of iterations, especially with bash)
Or
echo 'for(i=10;i>0;i-=2) i' | bc | paste -sd , -
(which would support numbers of any size, but note that past a certain number of digits (numbers greater than 1070 in the POSIX locale at least), lines would be wrapped with backslashes)
Method 5
Try with:
seq [OPTION]... FIRST INCREMENT LAST
Example:
$ seq 10 -1 1
Method 6
You can reverse the order using tac (cat in reverse). Even if seq should behave differently on various system, I think the following should be as portable as possible:
$ seq 1 10 | tr '12' ',' | sed 's/,$//'; echo 1,2,3,4,5,6,7,8,9,10 $ seq 1 10 | tac | tr '12' ',' | sed 's/,$//'; echo 10,9,8,7,6,5,4,3,2,1 $
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