I would like to print something as 5,4,3,2,1.
This is my program, but it prints the numbers vertically.
numbers=5
i=1
while [ "$i" -le "$numbers" ]
do
echo “$i”
i=$(( $i + 1 ))
done
Do you have any solution that could help me?
I would like to print something as 5,4,3,2,1.
This is my program, but it prints the numbers vertically.
numbers=5
i=1
while [ "$i" -le "$numbers" ]
do
echo “$i”
i=$(( $i + 1 ))
done
Do you have any solution that could help me?
There are many ways to do this, here are some:
Use seq
as @Gnouc suggested.
Use brace expansion and convert spaces to commas:
$ echo {5..1} | sed 's/ /,/g'
5,4,3,2,1
Use your script but change decrement the counter instead of incrementing it and change echo
to echo -n
(this will work for bash's builtin echo
but not for all echo
implementations):
i=5
while [ "$i" -gt 1 ]
do
echo -n "$i,"
let i--
done
echo "$i"
Use printf
instead:
i=5
while [ "$i" -gt 1 ]
do
printf "%s," "$i"
let i--
done
printf "%s\n" "$i"
Use a variable:
i=5
v=5
while [ "$i" -gt 1 ]
do
let i--;
v=$v,$i
done
echo $v
With seq
, you can do:
$ seq -s, 5 -1 1
5,4,3,2,1
And a perl
solution can be portable:
$ perl -e 'print join ",", reverse 1..5'
echo '5,4,3,2,1'
— this is the simplest answer that can work, as the question is stated. – ctrl-alt-delor Jul 18 '14 at 08:58echo
has a-n
option – ctrl-alt-delor Jul 18 '14 at 08:59