1

I have the following code in my batch script:

for %%m in (a b c) do (
    cd %%m
    dir
    for %%f in (*.zip) do rename "%%f" "%%m_%%f"
    dir
    cd ..
)

It is supposed to prepend the name of the folder a file lives in to the filename. I do so by running a nested for loop.

However, when I run the script I get the following outputs (shortened, for each variant of a, b, c):

05/15/2018  04:45 AM         5,213,422 build_1.0.0.zip
05/15/2018  04:45 AM         5,213,422 a_a_build_1.0.0.zip

so for whatever reason the rename gets executed two times per file and the second time on the already renamed file. With echo enabled we can actually see that happen:

C:\project>for %m in (a b c) do (
 cd %m     
 dir 
 for %f in (*.zip) do rename "%f" "%m_%f"  
 dir 
 cd .. 
)

...

C:\project>rename "build_1.0.0.zip" "a_build_1.0.0" 
C:\project>rename "a_build_1.0.0" "A_a_build_1.0.0" 

Why does that happen, and how can it be fixed (I would prefer to keep the nested loop if possible, as the script is normally a little longer - but even this shortened version shows this strange behaviour)

Felix
  • 6,885
  • 1
  • 29
  • 54
  • 5
    The `for` reads the directory one filename at a time. The filename generated then seems to be a new entry in the directory, so it's reprocessed. To overcome this, use a `for /f "delims=" %%f in ('dir /b /a-d *') do ...` as this builds a `dir` list in memory, then processes the list so the directory is not re-interpreted. – Magoo May 15 '18 at 13:23
  • 2
    Take a look also to this post: [At which point does `for` or `for /R` enumerate the directory (tree)?](https://stackoverflow.com/q/31975093) – aschipfl May 15 '18 at 13:41

0 Answers0