问题
(c)ToTheMaker
I found this code here and I'm going to use it but the only problems is I want it to have a user input that will create the folders
For example: "Enter number of folders:"
The value which the user will input will be used as a variable that will create the folders. How am I going to do that?
@ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION
SET groupsize=10
SET n=1
SET nf=0
FOR %%f IN (*.txt) DO (
IF !n!==1 (
SET /A nf+=1
MD Cake_!nf!
)
MOVE /Y "%%f" Cake_!nf!
IF !n!==!groupsize! (
SET n=1
) ELSE (
SET /A n+=1
)
)
ENDLOCAL
PAUSE
回答1:
Executing in a command prompt window either help set
or set /?
results in printing several help pages into the console window for command SET which should be read carefully. The help explains also set /P
for prompting user for a value or string.
@echo off
set "FolderCount=1"
set /P "FolderCount=Enter number of folders (default: %FolderCount%): "
for /L %%N in (1,1,%FolderCount%) do md "Folder%%N"
set "FolderCount="
This little batch code defines the environment variable FolderCount
with value 1 as default value which is used when the user hits just key RETURN or ENTER on prompt.
The user is asked next for the number of folders to create. The string entered by the user is assigned to environment variable FolderCount
. The user hopefully enters a positive number and not something different.
The FOR loop creates the folders in current directory with name Folder
and the current number appended which is automatically incremented by 1 on each loop run starting with value 1.
The last line deletes the environment variable FolderCount
not needed anymore.
For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.
echo /?
for /?
md /?
set /?
Edit: The final batch code for the entire task with moving the text files, too.
@echo off
rem Delayed expansion required for variable FolderIndex in FOR loop.
rem Command setlocal additionally creates a new environment variable
rem table with copying all existing variables to the new table.
setlocal EnableDelayedExpansion
rem Ask the batch user for number of subfolders to create and create them.
set "FolderCount=1"
set /P "FolderCount=Enter number of folders (default: %FolderCount%): "
for /L %%N in (1,1,%FolderCount%) do md "Folder%%N"
rem Move all *.txt files from current folder into the created subfolders.
set "FolderIndex=0"
for %%F in (*.txt) do (
set /A FolderIndex+=1
move /Y "%%~F" "Folder!FolderIndex!\%%~nxF"
if !FolderIndex! == %FolderCount% set "FolderIndex=0"
)
rem Restore previous environment which results in destroying
rem current environment table with FolderIndex and FolderCount.
endlocal
来源:https://stackoverflow.com/questions/33340248/how-to-make-my-user-input-as-a-variable-to-make-a-folder