once
once

Reputation: 1399

How to set a range of array elements in bash

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

Upvotes: 3

Views: 12135

Answers (3)

Jdamian
Jdamian

Reputation: 3125

declare -a MY_ARRAY=(
                      $(printf "%.2s" 0' '{1..11})    # 11 first zeroes
                      $(printf "%.2s" 1' '{12..25})   # 14 ones
                      $(printf "%.2s" 0' '{26..100})  # remaining zeroes
                    )

update
If the values 12 and 25 are in two variables, let's say, From and To:

declare -a MY_ARRAY=(
                       $( eval "{ printf %.2s 0_{1..$((From-1))};
                                  printf %.2s 1_{$From..$To};
                                  printf %.2s 0_{$((To+1))..100}; }" |
                                  tr _ ' '
                        )
                    )

Upvotes: 2

anishsane
anishsane

Reputation: 20980

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.

Upvotes: 6

Inian
Inian

Reputation: 85780

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

Upvotes: 6

Related Questions