ludmuterol
ludmuterol

Reputation: 15

How can I put a variable into my filename?

I want to copy a .bat file. The copy should be in the same path as the original file and have a random number as a name. This is my approach so far:

@echo
pause
SET nr = %RANDOM%
xcopy "%cd%\*.bat" "%nr%.bat" /q /y
pause

First question: What do I have to do, that the programm creates a .bat file with a number in front of the dot? (because now it creates just a .bat file without anything in front of the dot...)

Second question: How can I stop the question, if the target is a file or a directory?

Upvotes: 1

Views: 7245

Answers (2)

aschipfl
aschipfl

Reputation: 34979

Besides the fact that the line SET nr = %RANDOM% sets a variable called nrSPACE to a random number preceded by a SPACE, you actually do not need the interim variable nr, you can use RANDOM immediately instead.

To avoid the file/directory prompt of xcopy, use the copy command instead. Regard that this does not support a /Q switch. Instead you could use > nul to prevent copy from displaying something.

You do not need to precede the source *.bat with %CD%\, as %CD% just points to the current working directory, but *.bat alone points into that directory anyway.

Finally, I assume by @echo you actually mean @echo off to suppress command echoes.

So here is the fixed code:

@echo off
pause
copy /Y "*.bat" "%RANDOM%.bat" > nul
pause

Upvotes: 0

JosefZ
JosefZ

Reputation: 30238

SET nr = %RANDOM% creates variable with a trailing space in name: %nr % instead of %nr% and with a leading space in the value.

SET nr = %RANDOM%
rem   ↑ ↑           remove spaces
rem                 use following syntax instead
SET "nr=%RANDOM%"

You could use

xcopy "%cd%\*.bat" "%random%.bat" /q /y

but notice that both %nr% as well as %random% does not change. Following code snippet would be better

for /F "delims=" %%G in ( 'dir /b *.bat' ) do (
    SETLOCAL EnableDelayedExpansion
    xcopy "%%~G" "!random!.bat" /q /y
    ENDLOCAL
)

However, the %RANDOM% pseudovariable generates the same "random" number until the clock ticks over another second. (Notice also that the "random" numbers don't look all that random.)

Read the RANDOM article as well.

Upvotes: 1

Related Questions