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

2

7

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

Tripod answered 15/1, 2015 at 12:6 Comment(2)
Use DIR /B and pipe the list of names to a text file. Then iterate though that list. Currently you are iterating though the folder while you are making changes in that folder.Salerno
possible duplicate of For Loop in Batch File Renames One File TwiceStatuary
I
10

/f removes the issue of recapturing an existing file:

FOR /f "delims=" %%F IN ('DIR /a-d /b *.pdf')  DO (RENAME "%%F" "hello%%F")
Imitation answered 15/1, 2015 at 12:43 Comment(3)
Thanks this works! I read about /F "delims=", and I see you are also calling the command 'DIR /a-d /b *.pdf'. But could you please explain why mine does not work. In order to test I even tried to call in batch file FOR %%F IN (*.pdf) DO (ECHO "%%F") and it echoes only 3 files, so do you know why when using RENAME in place of ECHO it's renaming the 1st file twice?Tripod
RENAME changes the list of files your working through, echo does notImitation
FOR %%F ... get file names one by one from the disk directory so if the directory change, the names that FOR gets also may change, although this depends on several factors. FOR /F %%F ... in ('DIR') ... first execute the DIR command and then get file names from the list generated by it. Note that /F form requires to execute a second copy of cmd.exe in order to execute the DIR command and also create a temporary file that is deleted at end.Espalier
S
0
@echo off
echo.
echo. Add Whatever Prefix...
echo.
echo. You Want To Add...
echo.
echo. To The Filename...
echo.
set /p variable=" > "
setlocal enabledelayedexpansion
for /f "delims=" %%a in (' dir /b /a-d *.pdf') do (
  set oldName=%%a
  Set newName=%variable%!oldName!
  Ren "!oldName!" "!newName!"
)
exit

This works well..... Try It Out ... No Double Prefix... Ever.

Schoof answered 15/6, 2015 at 6:20 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.