i have an array of zeros
declare -a MY_ARRAY=( $(for i in {1..100}; do echo 0; done) )
how to set, for example, 12-25th to "1"? i've tried:
MY_ARRAY[12..25]=1
MY_ARRAY[12:25]=1
MY_ARRAY[12-25]=1
all not working..
the range 12-25 will be variables obtain from another file. I am looking for a simple solution better not involve in looping
please help
You can use eval here, in this manner:
eval MY_ARRAY[{12..25}]=1\;
If you want to know what is being evaled, replace eval by echo.
Using eval is generally considered as a no-no. But this use of eval here should be completely safe.
On another note,
for i in {1..100}; do echo 0; done
can also be re-written as
printf '%.1s\n' 0{1..100}
EDIT: For start & end being stored in variables, this could work:
$ declare -i start=12
$ declare -i end=12
$ eval $(eval echo "MY_ARRAY[{$start..$end}]=1;")
But in that case, you should really use loops. This answer is only for demonstration/information.
Simple one-liner:-
for i in {12..25}; do MY_ARRAY[$i]=1; done
Refer page Arrays for more manipulation examples.
If the start & end values are stored in variables, the brace expansion would not work. In that case, you should use for loop like this:
$ declare -i start=12
$ declare -i end=25
$ for ((i=$start;i<=$end;i++)); do MY_ARRAY[$i]=1; done
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