1

I tried to rename some files. But for some reason the first file will be renamed doubled.

%foldername% is a dynamic variable coming from a file path.

for %%a in (*.txt) do ren "%%a" "%foldername%_%%a"

Input:

newscript1.txt
newscript2.txt
newscript3.txt

Output:

foldername_foldername_newscript1.txt
foldername_newscript2.txt
foldername_newscript3.txt

Any ideas why the loop is doing two times for only the first file? Thanks for answers!

FZs
  • 16,581
  • 13
  • 41
  • 50
Birger
  • 11
  • 1
  • 1
    Two problems: 1. `for` does not build the list of files to iterate in advance, so when the renamed files still match the original pattern (`*.txt`), they might become renamed twice; 2. `for` (like most internal commands) checks both long and short file names (if such are enabled) against the given pattern, which might lead to doubled renaming too. Solution: `for /F "delims= eol=|" %%a in ('dir /B /A:-D-H-S "*.txt"') do ren "%%a" "%foldername%_%%a"` (because `for /F` does not begin to iterate until `dir` completed execution)… – aschipfl Mar 16 '21 at 07:37
  • Also related with respect to the possible 8.3 file name issue: [How does the Windows RENAME command interpret wildcards? \[Super User\]](https://superuser.com/q/475874) – aschipfl Mar 16 '21 at 21:08

0 Answers0