Bash: Is there a way to easily split a large array into smaller ones?

I was wondering if there is an easy way in bash to split a large array into several smaller ones. I now think something like this:

for ((i = 0; i<= (bigArrayLength/2); i++)) do bigArray[i] = smallArray[i] done for ((i = (bigArrayLength/2); i <=bigArrayLength; i++)) do bigArray[i] = secondSmallArray[i] done 

But there must be a better way to do this. Any suggestions? Thanks!

+4
source share
1 answer

If you have bash version 3.2 or later, you can do this using the new syntax "subitem" ( ${bigArray[@]:index_of_first_element:element_count} ), but be careful - if the element values ​​have any spaces in them, it can be terrible preprocessing.

So the idea goes line by line:

 cnt="${#bigArray[@]}" let cnt1="$cnt/2" let cnt2="$cnt - $cnt1 - 1" # this way we remove the rounding error if the count was odd and account for 0-based indexing smallArray=( "${bigArray[@]:0:$cnt1}" ) secondSmallArray=( "${bigArray[@]:$cnt1:$cnt2}" ) 
+4
source

All Articles