批处理:如何在 FOR 循环中附加字符串
Posted
技术标签:
【中文标题】批处理:如何在 FOR 循环中附加字符串【英文标题】:Batch: How to append string in FOR loop 【发布时间】:2018-02-27 00:27:00 【问题描述】:我在 FOR 循环中附加字符串时遇到问题。
我想为存储在数组中的每个名称创建子文件夹。 子文件夹属于用户指定名称的文件夹。
例如,如果我的数组中有以下名称: - 文件夹 1 - 文件夹 2 - 文件夹 3
我想要文件夹:
C:\我的文件夹\文件夹 1 C:\我的文件夹\文件夹 2 C:\MyFolder\文件夹 3
如前所述,“MyFolder”名称由用户在命令行中输入。
代码如下:
@echo off
@break off
@title Generate Billing Subfolders
@color 0a
@cls
setlocal EnableDelayedExpansion
SET "batch_path=%~dp0"
SET "first_folder=01. Folder1"
SET "second_folder=02. Folder2"
SET "third_folder=03. Folder3"
:: Create the new Working Data folder
SET /p new_folder_name= Enter Directory Name:
SET "full_path=%batch_path%%new_folder_name%"
ECHO Working...
IF NOT EXIST ("%full_path%") (
MKDIR %new_folder_name%
IF "!errorlevel!" EQU "0" (
ECHO Folder created successfully.
) ELSE (
ECHO Error while creating folder.
)
) ELSE (
ECHO Folder already exists.
)
SET "folders_list="%first_folder%" "%second_folder%" "%third_folder%""
FOR %%f in (%folders_list%) DO (
:: Displays the folder name in array correctly
ECHO %%f
:: Displays ECHO is off. Why?
CALL SET "updated_full_path=%full_path%\%%f"
ECHO %updated_full_path%
PAUSE
)
PAUSE
EXIT
【问题讨论】:
【参考方案1】:既然你已经有enabled delayed expansion:
setlocal EnableDelayedExpansion
....
FOR %%f in (%folders_list%) DO (
:: Displays the folder name in array correctly
ECHO %%f
:: Displays ECHO is off. Why?
SET "updated_full_path=!full_path!\%%f"
ECHO !updated_full_path!
PAUSE
)
PAUSE
【讨论】:
谢谢!我不理解 EnableDelayedExpansion 的目的并使用“!...!”。我将按照您的指示用我的问题的答案更新代码。以上是关于批处理:如何在 FOR 循环中附加字符串的主要内容,如果未能解决你的问题,请参考以下文章