Is there a way to specify a certain range of numbers using array in a script? [closed]
Solution 1:
I think you're asking how to get the first N elements of a bash array. If so, this should work:
$ array=( $(seq 1 30 ) )
$ echo ${array[@]}
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
$ echo ${array[@]:0:20}
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
The general format is ${array[@]:START:LENGTH}
. That will return the LENGTH next elements of array starting from START.
So, to add the first 20, you could do (note that I'm starting from 0, not 1 since arrays begin at 0. I suggest you correct your script and set count=0
at the beginning instead of count=1
; if you don't want to, change the 0
below to a 1
):
for i in ${number[@]:0:20}; do
sum=$((sum + i))
done
echo $sum
Alternatively, you could just iterate over the first 20 elements of the array:
for((i=0;i<20;i++))
do
sum=$(( sum + number[$i] ))
done
echo "$sum"
Both methods assume you are adding integers. Bash doesn't deal with floating point numbers so they will break if you try to add fractions. If that's an issue, use @hemayl's clever trick or any other program that can do math. For example:
echo "${number[@]:0:20}" | perl -lane '$k+=$_ for @F; print $k'
Solution 2:
To add the first 20 numbers of the array number
:
echo "${number[@]:0:20}" | tr ' ' '+' | bc
Or
tr ' ' '+' <<<"${number[@]:0:20}" | bc
"${number[@]:1:20}"
gets the first 20 elements of the arraytr ' ' '+'
converts all spaces into+
so that we can use it as input tobc
to get the addition done