How do you split an array in groups of n

This is similar to Add '\ n' after a certain number of delimiters , however, it suggests a number if the elements in the group are programmed.

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 to do this with bash?

I tried several options. Here's the last crash (tmp [] is an array):

for e in ${tmp[@]}; do 
  for i in $(eval echo "{0..$groupsof}"); do 
    foo[$i]=$e; 
  done
done
+4
source share
3 answers

Use a substring extension. "${array[@]:offset:length}"gets items lengthstarting from 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
+7
source
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
+1
source

It works:

echo aaa,bbb,ccc,ddd,eee,fff,ggg,hhh,iii,jjj,kkk,lll,mmm | sed 's/,/,\n/g' | paste -d "" $(yes - | head -4 | paste -s) | sed 's/,$//g'
0
source

Source: https://habr.com/ru/post/1541182/


All Articles