Windows batch to add prefix to file names, why added twice?

Marco Demaio picture Marco Demaio · Jan 15, 2015 · Viewed 21.7k times · Source

In order to add a simple "hello" prefix to all pdf files in a folder I'm using this batch file:

FOR %%F IN (*.pdf) DO (RENAME "%%F" "hello%%F")

Saved this into a "rename.bat" file and placed it into the folder I need the files to be renamed. Then I just double click on "rename.bat".

This almost works but the 1st file gets the prefix added twice.

Let's say in the folder I have: A.pdf, B.pdf, C.pdf, they get converted into:

  • hellohelloA.pdf
  • helloB.pdf
  • helloC.pdf,

Do you know what's wrong in the batch file?


I noticed it always does this when files are more than one. It works ok when there is only one file in the folder, but it is not very useful :-).

Answer

Alex K. picture Alex K. · Jan 15, 2015

/f removes the issue of recapturing an existing file:

FOR /f "delims=" %%F IN ('DIR /a-d /b *.pdf')  DO (RENAME "%%F" "hello%%F")