2

I am trying to write a simple for command which renames files found in a folder with a prefix like:

c0001.mp4 becomes card1-c0001.mp4

It works, however, the first file gets renamed twice: card1-card1-c0001.mp4 when I run this code. It doesn't matter what folder or file name, the first file in sequence is always double renamed.

All other files are fine. if I change the command to an echo, it looks right. What am I missing?

for %%a IN ("F:\2016-Sep-18\card1\*.mp4") do ren %%a card1-%%~nxa 
N. Johnson
  • 101
  • 1
  • 7
  • 2
    Related: [At which point does `for` or `for /R` enumerate the directory (tree)?](http://stackoverflow.com/q/31975093) – aschipfl Sep 19 '16 at 05:37

1 Answers1

6

The batch reads the directory and renames the first file, creating a new filename. This new filename is appended to the directory and then the original is deleted. The next name encountered is processed, but the new name is placed in the now-empty first entry vacated by the deletion of the first filename. Eventually, the last filename in the directory is processed - and that is the first-renamed file.

To cure it, try

set "targetdir=F:\2016-Sep-18\card1"
for /F %%a IN ('dir /b/a-d "%targetdir%\*.mp4"') do ECHO(ren %targetdir%\%%a card1-%%~nxa

Note here that I've assigned the directoryname to a variable for convenience (you'd only need to change it once rather than in multiple positions). I've also simply echoed the rename for testing and verification purposes.

The idea here is that the dir command output (no directorynames, basic format) is created first and placed in memory. This "file" is then processed, so the dir is complete before the renaming operation begins.

Magoo
  • 77,302
  • 8
  • 62
  • 84