将一个大数组拆分为三个

时间:2017-01-04 17:54:19

标签: bash

我需要将一个大数组分成三个小数组。我尝试了什么:

STAThread

这很好,它让我回答:

#!/bin/bash
declare -a bigarray
bigarray=( 0 1 2 3 4 5 6 7 8 9 10 11 )
total=${#bigarray[@]}
let t1="$total / 3"
declare -a fstsmall
fstsmall=( "${bigarray[@]:0:$t1}" )
let t2="$total - $t1 - 1"
declare -a sndsmall
sndsmall=( "${bigarray[@]:$t1:$t1}" )
let t3="$t2 + 1"
let theend="$total - $t2"
echo $theendwq
trdsmall=( "${bigarray[@]:$t3:$theend}" )
echo "${fstsmall[@]}"
echo "${sndsmall[@]}"
echo "${trdsmall[@]}"
exit 0

但是如果我将第12个元素添加到大数组中,它会突然变成:

0 1 2 3
4 5 6 7
8 9 10 11

省略第8个元素。我怀疑我需要循环,因为元素的数量是动态的。

1 个答案:

答案 0 :(得分:0)

让bash为你计算最后一个切片的大小。我还将您的代码切换到$(()) arithmetic expansion,因为这是我熟悉的。

#!/bin/bash
declare -a bigarray
bigarray=( 0 1 2 3 4 5 6 7 8 9 10 11 12)    # also works without the 12
total=${#bigarray[@]}
slice_size=$(($total/3))    #Arithmetic expansion instead of "let"
declare -a fstsmall
fstsmall=( "${bigarray[@]:0:$slice_size}" )
#let t2="$total - $t1 - 1"    # Don't need this any more
declare -a sndsmall
sndsmall=( "${bigarray[@]:$slice_size:$slice_size}" )
#let t3="$t2 + 1"
#let theend="$total - $t2"
last_start=$(($slice_size * 2))
echo $last_start
trdsmall=( "${bigarray[@]:$last_start}" )   
    # Leaving off the :length gives you the rest of the array
echo "${fstsmall[@]}"
echo "${sndsmall[@]}"
echo "${trdsmall[@]}"