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
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With