Static vs dynamic for

Jun 24, 2008
220
0
Siegen, Germany
I often use a - self-written - Perl script that renames files according to some complex condition. It is called like so:

FOR %i IN (*.pdf) rename.pl "%i"

At times it may happen that a file "abc.pdf" (e.g.) is renamed to "xyz.pdf" (e.g.). This renamed file would then be again - and unwantedly - processed by the loop as it newly appears in FOR's list of files (aka the directory).

Is there a way to have FOR use a static list of files as compared to its - obviously - dynamic one? I found no clue in the docs so far.

I know, I could change my Perl script and have IT iterate over directory...
 
May 20, 2008
3,515
3
Elkridge, MD, USA
Sorry, that's one of the oldest warnings in 4DOS and still current in the latest TCC; and it was always the way COMMAND.COM and CMD.EXE worked as well. Its reason is that it is how the file system operates.

When necessary, I circumvent it by creating my own static list. You may wish to use the feedback to request such a new feature; if you do, remember that other commands, e.g., move, are subject to the like behavior.
 

rconn

Administrator
Staff member
May 14, 2008
11,502
115
You can work around it one of two ways:

1) Create a file list for FOR to parse:

Code:
dir /b *.pdf > pdf.files
for %i in (@pdf.files) rename.pl "%i"
2) Have TCC sort the list (which creates a temp file automatically):

Code:
for /o:n in (*.pdf) rename.pl "%i"
 

Charles Dye

Super Moderator
Staff member
May 20, 2008
3,980
53
Albuquerque, NM
prospero.unm.edu
Another approach is to create a temp directory on the same drive, then rename the files into that location. (Yes, REN can move files as it renames.) When the loop finishes, MOVE all the renamed files from the temp directory back to their original home, then remove the temp directory.
 

samintz

Scott Mintz
May 20, 2008
1,372
12
Solon, OH, USA
Another option is to use DO /p:
Code:
do f in /p dir /b *.pdf (rename.pl "%f")

or using FOR:

for /f %f in ('dir /b *.pdf') do rename.pl "%f"
 
May 20, 2008
3,515
3
Elkridge, MD, USA
2) Have TCC sort the list (which creates a temp file automatically):

Code:
for /o:n in (*.pdf) rename.pl "%i"
and it has been right in the HELP manual since version 11 - I do need to RTFM!
"The /O:... option saves all of the matching filenames and then performs the requested operation. This avoids the potential problem of processing files more than once."