在 Windows Batch 中创建列表或数组 [英] Create list or arrays in Windows Batch
问题描述
我可以像这样在批处理文件中声明一个列表或数组吗:
Can I declare a list or array in a batch file like this:
set list = "A B C D"
然后我需要将这些写到一个文件中,中间有空格:
And then I need to write these to a file, with the spaces between:
A
B
C
D
推荐答案
是的,您可以同时使用两种方法.如果你只是想将元素分开并在单独的行中显示它们,列表更简单:
Yes, you may use both ways. If you just want to separate the elements and show they in separated lines, a list is simpler:
set list=A B C D
for
命令可以轻松处理由空格分隔的值列表:
A list of values separated by space may be easily processed by for
command:
(for %%a in (%list%) do (
echo %%a
echo/
)) > theFile.txt
你也可以这样创建一个数组:
You may also create an array this way:
setlocal EnableDelayedExpansion
set n=0
for %%a in (A B C D) do (
set vector[!n!]=%%a
set /A n+=1
)
并以这种方式显示数组元素:
and show the array elements this way:
(for /L %%i in (0,1,3) do (
echo !vector[%%i]!
echo/
)) > theFile.txt
有关批处理文件中数组管理的更多详细信息,请参阅:cmd.exe(批处理)脚本中的数组、链表等数据结构
For further details about array management in Batch files, see: Arrays, linked lists and other data structures in cmd.exe (batch) script
注意!您必须知道set
命令中包含的所有字符都插入到变量名中(在等号的左侧),或插入到变量值中.例如,这个命令:
ATTENTION! You must know that all characters included in set
command are inserted in the variable name (at left of equal sign), or in the variable value. For example, this command:
set list = "A B C D"
创建一个名为list
(列表空间)的变量,其值为"A B C D"
(空格、引号、A 等).因此,最好不要在 set
命令中插入空格.如果需要将值括在引号中,则必须将变量名及其值括起来:
create a variable called list
(list-space) with the value "A B C D"
(space, quote, A, etc). For this reason, it is a good idea to never insert spaces in set
commands. If you need to enclose the value in quotes, you must enclose both the variable name and its value:
set "list=A B C D"
PS - 你不应该使用 ECHO.
来留空行!另一种方法是 ECHO/
.有关这一点的更多详细信息,请参阅:http://www.dostips.com/forum/viewtopic.php?f=3&t=774
PS - You should NOT use ECHO.
in order to left blank lines! An alternative is ECHO/
. For further details about this point, see: http://www.dostips.com/forum/viewtopic.php?f=3&t=774
这篇关于在 Windows Batch 中创建列表或数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!