'How to randomly generate names for each file in folder in batch file?
I want to rename all files in folder to random name but it wants to rename all the files to the same name:
ren "c:\Test\*.txt" %Random%.txt
pause
Output:
C:\Users\Oliver\Desktop>ren "c:\Test\*.txt" 9466.txt
A duplicate file name exists, or the file
cannot be found.
A duplicate file name exists, or the file
cannot be found.
A duplicate file name exists, or the file
cannot be found.
A duplicate file name exists, or the file
cannot be found.
A duplicate file name exists, or the file
cannot be found.
A duplicate file name exists, or the file
cannot be found.
C:\Users\Oliver\Desktop>pause
Press any key to continue . . .
Does someone know how to randomly generate names for each file in folder in batch file?
Solution 1:[1]
In a command line like ren "C:\Test\*.txt" "%RANDOM%.txt"
, %RANDOM%
is expanded only once and so it tries to rename every file to the same name.
To rename each file individually, you need to loop through all the files.
For this to work, delayed expansion is required -- see set /?
.
Here is the batch file solution:
@echo off
setlocal EnableDelayedExpansion
for %%F in ("C:\Test\*.txt") do (
ren "%%~F" "!RANDOM!.txt"
)
endlocal
And here is the command line variant:
cmd /V:ON /C for %F in ("C:\Test\*.txt") do ren "%~F" "!RANDOM!.txt"
Note that !RANDOM!
may also return duplicate values which is not regarded in the above codes.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |