For loop sequence issue

Hi. I have a bunch of tif images in the directory with the following naming convention:

1.tif
2.tif
3.tif
.
.
.
n.tif

There are over 1000 tif images in this dir. I'm running a for loop to rename *.tif in this dir to <YYYYMMDD><NNNN>.tif, where YYYYMMDD is the current date (duh), and NNNN is a 4-digit sequence number beginning with 1 and incrementing with each tif image.

I also have an input csv file that references the images. I'm reformatting the csv file and including it in a zip file at the end of processing, which also contains the re-named zip files.

The problem I'm having is that the output csv matches the data in the input csv (and re-formatted properly), but the transactions in the output csv reference the wrong images.

I've discovered that the problem is in the For loop. This is the code:

cd $IMGPATH
   for file in $IMGPATH/*.tif ; do
      count=$((count + 1))
      count_str=$(printf "%04d" $count)
      mv $file $LBOX$DATEDIR$count_str"0.tif"
   done

The problem is that this sequences the files in the following order:

1.tif
10.tif
100.tif
1000.tif
etc

So my second transaction in the output csv file references the 10th image in the directory, the 3rd transaction in the csv file references the 100th image in the directory, and so on.

How do I make the loop sort by image number properly?

Rather than counting thru the files, why not break apart the filenames to get the numeric portion? Something like:

myvar=`cut -d"." -f1`

and then format your output name.

name convention (after confirm, remove "echo" from the script)

$IMGPATH=/XXXX/XXX
DATE=$(date +%Y%m%d)

cd $IMGPATH

for file in $(ls *.tif)
do
    NewName=$( echo $file |awk -v D="$DATE" -v L=$LBOX -F \. '{printf "%s-%s-%04d.%s",L,D,$1,$2}')
    echo mv $file $NewName
done

For the CVS and zip, you need explain more clearly what you ask for.

Yes, rdc.... you're on the right track. This was the actual solution that I went with:

   cd $IMGPATH
   for file in $(ls | sort -n); do
      count=$((count + 1))
      count_str=$(printf "%04d" $count)
      mv $file $LBOX$DATEDIR$count_str"0.tif"
   done

The problem was that the transactions in the csv file had the tif images listed as 1.tif, 2.tif, 3.tif, ..., n.tif, but the previous code was sorting them as 1.tif, 10.tif, 100.tif, etc. So the 2nd transaction in the output csv referenced the 10th tif image, the 3rd referenced the 100th tif image, and so on.

It has to do with the way unix sorts (collates) values in a "for i in *.tif..." looping scenario. If one needs to have the numeric portion of the file names to maintain their sequence value, then my code above works.

Thanks for everyone's help.

for sort, you can

sort -n