for loop on files sometimes reinjects renamed files in the loop !

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

Post Reply
Message
Author
Pilou
Posts: 6
Joined: 07 Jan 2014 08:42

for loop on files sometimes reinjects renamed files in the loop !

#1 Post by Pilou » 20 Oct 2017 05:36

All is in the title... Hereunder shows a very strange behavior... One file, two loopings...
Is this a bug ? Is there a workaround available ?

Code: Select all

C:\Temp\test>ver

Microsoft Windows [Version 6.1.7601]



C:\Temp\test>type c:\temp\test.bat
@echo off
setlocal enabledelayedexpansion

dir *.avi

for %%a in (*.avi) do (
   set "A=%%a"
   set "B=!A:~14,999!"
   echo FICHIER # !B!
   ren "%%a" "!B!"
)



C:\Temp\test>c:\temp\test.bat
 Volume in drive C is C
 Volume Serial Number is CABD-7C08

 Directory of C:\Temp\test

19/05/2005  12:14        10 342 246 DUREE=53______ssssssssssss.avi
               1 File(s)     10 342 246 bytes
               0 Dir(s)  113 463 861 248 bytes free
FICHIER # ssssssssssss.avi
FICHIER # vi


C:\Temp\test>dir
 Volume in drive C is C
 Volume Serial Number is CABD-7C08

 Directory of C:\Temp\test

20/10/2017  13:29    <DIR>          .
20/10/2017  13:29    <DIR>          ..
19/05/2005  12:14        10 342 246 vi
               1 File(s)     10 342 246 bytes
               2 Dir(s)  113 463 640 064 bytes free



Last but not least, if I replace "s" by "a" in the filename, the problem doesn't occur, and only one "ren" is done (transforming "DUREE=53______aaaaaaaaaaaa.avi" to "aaaaaaaaaaaa.avi" as expected)

Thanx for your help !

Squashman
Expert
Posts: 4486
Joined: 23 Dec 2011 13:59

Re: for loop on files sometimes reinjects renamed files in the loop !

#2 Post by Squashman » 20 Oct 2017 08:17

Yes that is the way the FOR command works. In order for you it not pickup the newly renamed files again, you need to use a FOR /F command and execute the DIR command within it.

Code: Select all

for /f "delims=" %%a in ('dir /a-d /b *.avi') do (

Post Reply