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 
1

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.