我正在尝试创建一个脚本,该脚本从list.txt(由回车分隔的文件目录名称列表)创建一组文件夹,每个文件夹都包含由用户命名的特定数量的子目录。
此脚本可以完全做到这一点并正常工作:
@echo off
setlocal enableextensions
set /P q="How many subdirectories would you like to add in each folder?[0/1/2/3]"
if /I "%q%" EQU "0" goto :somewhere0
if /I "%q%" EQU "1" goto :somewhere1
if /I "%q%" EQU "2" goto :somewhere2
if /I "%q%" EQU "3" goto :somewhere3
if errorlevel 1 goto :problem
:somewhere0
echo All done! Press any key to exit.
pause
exit
...(code cut for brevity)
:somewhere3
set /P c="What is the name of the first subdirectory?"
for /F "tokens=1 delims=," %%d IN (list.txt) DO md "%%c"\"%%d"
set /P c="What is the name of the second subdirectory?"
for /F "tokens=1 delims=," %%d IN (list.txt) DO md "%%c"\"%%d"
set /P c="What is the name of the third subdirectory?"
for /F "tokens=1 delims=," %%d IN (list.txt) DO if not exist %%d md "%%d" cd "%%d" md "%%c" cd ..
if errorlevel 1 goto :problem
goto :somewhere0
...
您得到图片。但是,我试图循环执行此操作,而不是对每个实例进行硬编码。我开发的代码如下:
@echo off
setlocal enableextensions
set "var=string"
set /P q="How many subdirectories would you like to add in each folder?"
for /l %%x in (1, 1, %q%) do (
set /P c="What is the name of subdirectory %%x?"
for /F "tokens=1 delims=," %%d IN (list.txt) DO md "%%d\%c%"
)
尝试在循环中间回显变量%% d或%c%不会产生任何结果。陌生人,脚本实际上创建了顶级目录-即,此代码运行
for /F "tokens=1 delims=," %%d IN (list.txt) DO md "%%d
,但未显示子目录。有建议吗?
请注意,我不诚实地知道为什么第一个工作代码要求这种特殊顺序的%符号,但这是我使其工作的唯一方法。
答案 0 :(得分:1)
enabledelayedexpansion
是您想要的。
@echo off
setlocal enableextensions enabledelayedexpansion
set "var=string"
set /P q="How many subdirectories would you like to add in each folder? "
for /l %%x in (1, 1, %q%) do (
set /P c="What is the name of subdirectory %%x? "
for /F "tokens=1 delims=," %%d IN (list.txt) DO md "%%d\!c!"
)
从cmd.exe
的如果运行setlocal /?
,您将获得更多帮助,但是简而言之,enabledelayedexpansion
启用了延迟的环境变量扩展。这将导致批处理文件中的变量在执行时而不是在解析时进行扩展。也可以在命令行上以CMD /V:ON
启用,而不是批量启用。
您基本上告诉命令处理器延迟变量的解析,直到它执行它们为止。 %
用!
替换,以显示在扩展中使用哪些变量。