Using nested for loop to iterate over file names

I'm trying to grab a list of file names from a directory, then process those files 5 at a time. In the link below. Instead of using files I'm using the files array which contains 15 strings starting with AAA .

So I'm trying to assign $fileset 5 of the strings at a time to pass to a command. So $fileset looks like this the first pass:

AAA BBB CCC DDD  EEE

Then the second iteration:

FFF GGG HHH III JJJ
files=( AAA BBB CCC DDD EEE FFF GGG HHH III JJJ KKK LLL MMM NNN OOO )

   echo "Total files in array : ${#files
[*]}"
   total=${#files
[*]}

   for (( i = 0 ; i < $total ; i++ )) do
   fileset=""

      for (( j = $i ; j < 5 ; j++ )) do
         fileset=$fileset${files[$j]}
      done

      echo $fileset
      fileset=""

   done

Your output will be all below each other:

Try to modify this:

MAX=3
CNT=0
LIST="aaa bbb ccc ddd eee fff ggg hhh iii"

for L in $LIST;do
	if [[ $CNT -lt $MAX ]]
	then	printf "$L "
	else	printf "\n$L "
		CNT=0
	fi
	CNT=$(( $CNT + 1 ))
done
printf "\n"

Outputs as:

sh ~/blubber.sh 

aaa bbb ccc 
ddd eee fff 
ggg hhh iii 

gl & hth

Telling us what OS and shell you're using helps us create a solution that will work in your environment.

With a 1993 or later version of ksh or with a recent bash , here are a couple of ways to do what you seem to want:

#!/bin/ksh
files=( AAA BBB CCC DDD EEE FFF GGG HHH III JJJ KKK LLL MMM NNN OOO PPP QQQ)

total=${#files[@]}
echo "Total files in array : $total"

echo 'Using nested for loops...'
fileset=""
for (( i = 0 ; i < total ; i += 5 ))
do	for ((j = 0; j < 5 && (i + j) < total; j++))
	do	fileset="$fileset ${files[i + j]}"
	done
	echo $fileset
	fileset=""
done

echo 'Using array subsets...'
for ((i = 0; i < total; i += 5))
do	fileset="${files[@]:i:5}"
	echo "$fileset"
done

which (with both of those shells) produces the output:

Total files in array : 17
Using nested for loops...
AAA BBB CCC DDD EEE
FFF GGG HHH III JJJ
KKK LLL MMM NNN OOO
PPP QQQ
Using array subsets...
AAA BBB CCC DDD EEE
FFF GGG HHH III JJJ
KKK LLL MMM NNN OOO
PPP QQQ

Try also (using Don Cragun's array):

echo "${files[@]}" | xargs -n5 | while read -a ARR; do echo ${#ARR[@]}, ${ARR[@]}; done
5, AAA BBB CCC DDD EEE
5, FFF GGG HHH III JJJ
5, KKK LLL MMM NNN OOO
2, PPP QQQ

This works for bash , but not for ksh . With ksh you'd need to use:

read -A ARR

instead of:

read -a ARR