Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 :-).

like image 249
Marco Demaio Avatar asked Jan 15 '15 12:01

Marco Demaio


People also ask

How do I batch rename files sequentially?

You can press and hold the Ctrl key and then click each file to rename. Or you can choose the first file, press and hold the Shift key, and then click the last file to select a group.

Is there a way to rename a bunch of files at once?

To rename multiple files from File Explorer, select all the files you wish to rename, then press the F2 key. The name of the last file will become highlighted. Type the new name you wish to give to every file, then press Enter.

What does %1 do in batch file?

When used in a command line, script, or batch file, %1 is used to represent a variable or matched string. For example, in a Microsoft batch file, %1 can print what is entered after the batch file name.


1 Answers

/f removes the issue of recapturing an existing file:

FOR /f "delims=" %%F IN ('DIR /a-d /b *.pdf')  DO (RENAME "%%F" "hello%%F")
like image 172
Alex K. Avatar answered Sep 22 '22 09:09

Alex K.