Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you break an array in groups of n

Tags:

arrays

bash

This is similar to Add '\n' after a specific number of delimiters, however, lets assume the number if elements in a group is programmable.

we have:

aaa,bbb,ccc,ddd,eee,fff,ggg,hhh,iii,jjj,kkk,lll,mmm
g=4

we want

aaa,bbb,ccc,ddd
eee,fff,ggg,hhh
iii,jjj,kkk,lll
mmm

How do we accomplish this with bash?

I have tried a number of options. Here's the latest failure (tmp[] is the array):

for e in ${tmp[@]}; do 
  for i in $(eval echo "{0..$groupsof}"); do 
    foo[$i]=$e; 
  done
done
like image 863
Jason Michael Avatar asked May 19 '14 21:05

Jason Michael


2 Answers

Use substring expansion. "${array[@]:offset:length}" gets you length elements starting at offset:

#!/bin/bash

array=(aaa bbb ccc ddd eee fff ggg hhh iii jjj kkk lll mmm)
g=4

for((i=0; i < ${#array[@]}; i+=g))
do
  part=( "${array[@]:i:g}" )
  echo "Elements in this group: ${part[*]}"
done
like image 90
that other guy Avatar answered Oct 19 '22 19:10

that other guy


kent$  array=(aaa bbb ccc ddd eee fff ggg hhh iii jjj kkk lll mmm)

kent$  echo "${array[@]}"|xargs -n4                               
aaa bbb ccc ddd
eee fff ggg hhh
iii jjj kkk lll
mmm
like image 25
Kent Avatar answered Oct 19 '22 18:10

Kent