2017-01-04 1 views
1

Ich muss ein großes Array in drei kleine aufteilen. Was ich habe versucht:Teilen Sie ein großes Array in drei

#!/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 

Das ist in Ordnung, es gibt mir:

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

Aber wenn ich 12. Element zu großen Array hinzufügen, es brach in:

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

8. Element wird weggelassen. Ich vermute, ich brauche dafür Schleifen, da die Anzahl der Elemente dynamisch ist.

+0

Willkommen auf der Website, und danke für die Frage nach einer detaillierten Frage! Schaut euch die [Tour] (https://Stackoverflow.com/tour) an, um mehr darüber zu erfahren, was euch hier erwartet. – cxw

Antwort

0

Lassen Sie Bash berechnen Sie die Größe der letzten Scheibe für Sie. Ich habe Ihren Code auch auf $(()) arithmetic expansion umgestellt, da ich damit vertraut bin.

#!/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[@]}" 
+0

Danke, das habe ich gebraucht! – Airee

Verwandte Themen