0

I am storing a file list in an array . What I'd like to do is loop through a process that will read N elements of an array and delete all the elements it just read. The Exception is the last iteration , when you come to the last iteration of the loop - whatever remains in the array - just split that out .

th=$1
ar=('f1' 'f2' 'f3' 'f4' 'f5' 'f6')

for ((i=1; i<=$th; i++)); do

<stuff>
if [ "$i" -eq "$th" ]

then
# if its the last iteration of the loop.Whatever remains in the array - spit that out 
echo " `echo ${ar[*]}`"    >> somefile 

# it its anything short of the last iteration.Read N elements of the array at a time 
# and then delete them 
else
echo " `echo ${ar[*]:0:$N}`  " >> somefile 
     for ((x=0; x<=$N; x++)) ; do
     unset ar[$x]
     done

fi

The results are very erratic. Even when I use this approach and test if separately

 for ((x=0; x<=$N; x++)) ; do
     unset ar[$x]
     done

It will delete the WHOLE array EXCEPT the $Nth element I am new to arrays in shell. Any help is gladly appreciated

Håkon Hægland
  • 39,012
  • 21
  • 81
  • 174
user1874594
  • 2,277
  • 1
  • 25
  • 49

1 Answers1

2

Try the following:

#! /bin/bash

th=3
N=2
ar=('f1 f' 'f2' 'f3' 'f4 x' 'f5' 'f6' 'f7')

for ((i=0; i<$th; i++)); do
    if (( $i == $(($th - 1)) )) ; then
       echo "${ar[*]}" 
    else
       echo "${ar[*]:0:$N}" 
       ar=( "${ar[@]:$N}" )
    fi
done

Output:

f1 f f2
f3 f4 x
f5 f6 f7

Note:

  • Arrays in bash are zero based.
  • Indices are not adjusted after unset ar[$x], therefore it would be easier to reconstruct the array as ar=( "${ar[@]:$N}" ) to force new indices to start at zero..

Update:

Or you could avoid the reconstruction of the array using:

#! /bin/bash

th=3
N=2
ar=('f1 f' 'f2' 'f3' 'f4 x' 'f5' 'f6' 'f7')

for ((i=0; i<$th; i++)); do
    if (( $i == $(($th - 1)) )) ; then
       echo "${ar[*]:$(($i * $N))}" 
    else
       echo "${ar[*]:$(($i * $N)):$N}" 
    fi
done
Håkon Hægland
  • 39,012
  • 21
  • 81
  • 174