Batch files: FOR loop counting

Microsoft Windows xp professional w/serv...
November 25, 2009 at 14:09:47
Specs: Windows XP, Phenom II/4GB
I am trying to write a batch file that will iterate through the files in a folder. As soon as it hits the 4th one (and subsequent ones) it will move that file to a sub directory "OLD." Since I order the DIR command by date it will only leave the 3 newest files untouched in the folder.

here is what I have...



FOR /F "tokens=*" %%A IN ('DIR c:\AVI\*.AVI /b /a-d /o-d') do (
SET /a I+=1
IF %I% GTR 3 ( MOVE "%%A" OLD )

echo count = %I%

The problem is that for some reason the value of %I% stays unchanged until after the FOR loop is completed. Within the loop the echo statement ECHO I=%I% always returns 'I=0'. Since %I% is zero the conditional never executes the MOVE command.

Strangely, after the loop exits the %I% variable suddenly decides to co-operate and returns the proper file count. There are 5 files in the folder so the echo command returns 'count = 5'

can someone fix this? or give me an alternative solution?

See More: Batch files: FOR loop counting

Report •

November 25, 2009 at 14:59:13
@echo off & setLocal EnableDELAYedExpansion

for /f "skip=3 tokens=* delims= " %%a in ('dir/b/a-d/o-d') do (
move %%a OLD

Helping others achieve escape felicity


Report •

November 25, 2009 at 19:59:02
ya M2 is right, that's exactly the issue that delayedexpansion addresses: the timing of the variable expansion.

be sure to change the percents to exlms:

IF %I% GTR 3 ( MOVE "%%A" OLD )

echo count = %I%

echo I=!I!
if !I! gtr 3 (move "%%A" OLD)
echo count = !I!

(note that the percents on var. A are not affected)

Report •

November 26, 2009 at 07:19:18
Thanks guys. You really helped me out!
Its working great now!

Report •

Related Solutions

Ask Question