我在标题中提到了常量索引,因为StackOverflow中所有与批处理文件中的数组索引有关的问题都集中在使用循环中的变量索引访问数组上。
我刚开始批量编写脚本。如果数组被初始化为列表(在一行中),而不是单独初始化每个元素,我希望打印具有常量索引的数组值。我编写了一个片段,其中可以打印arr
的值,但不能打印list
的值。
@echo off
set arr[0]=1
set arr[1]=2
set arr[2]=3
set list=1 2 3 4
REM Result is 2
echo %arr[1]%
REM Won't print
echo %list[1]%
发布于 2018-07-07 17:41:36
字符串中的列表不是数组,两天前的这个答案演示了如何将字符串列表转换为数组。
若要使基于数组索引零的数组使用此更改版本
:: SO_51225079.cmd
@echo off & Setlocal EnableDelayedExpansion
set arr[0]=1
set arr[1]=2
set arr[2]=3
set i=-1&set "list= 1 2 3 4"
Set "list=%list: ="&Set /a i+=1&Set "list[!i!]=%"
set list
REM Result is 2
echo %arr[1]%
REM Won't print
echo %list[1]%
样本输出:
> SO_51225079.cmd
list[0]=1
list[1]=2
list[2]=3
list[3]=4
2
2
发布于 2018-07-07 17:42:36
您可能会混淆批处理和PowerShell。在PowerShell中,是的,可以在一行上初始化一个数组:
$list = 1, 2, 3, 4
$list[1]
# output here would be 2
在批处理脚本语言中,没有数组对象。您可以通过具有类似或顺序命名的标量变量来模拟数组,但是批处理语言没有提供诸如split()
或splice()
或push()
或类似的方法。
通常在批处理中,在空格(或逗号或分号)上拆分字符串是通过使用for
循环标记来完成的。
@echo off & setlocal
rem // Quoting "varname=val" is the safest way to set a scalar variable
set "list=1 2 3 4"
rem // When performing arithmetic using "set /a", spacing is more flexible.
set /a ubound = -1
rem // Split %list% by tokenizing using a for loop
for %%I in (%list%) do (
set /a ubound += 1
rem // Use "call set... %%ubound%%" to avoid evaluating %ubound% prematurely.
rem // Otherwise, %ubound% is expanded when the for loop is reached and keeps the
rem // same value on every loop iteration.
call set "arr[%%ubound%%]=%%~I"
)
rem // output results
set arr[
setlocal enabledelayedexpansion
rem // You can also loop from 0..%ubound% using for /L
for /L %%I in (0, 1, %ubound%) do echo Element %%I: !arr[%%I]!
endlocal
另外,在代码块中,我演示了延迟批量扩展变量的两种方法--使用call set
和setlocal enabledelayedexpansion
,在需要延迟检索的地方使用感叹号。有时候知道两者都是有用的。enabledelayedexpansion
方法通常更易读/更容易维护,但在某些情况下,可能存在感叹号(如文件名)的值。因此,我尽量避免对整个脚本启用延迟扩展。
LotPings的回答很聪明,但应用程序有限。它的工作方式是,使用子串替换将list
的值设置为一系列命令(由&分隔)。不幸的是,它破坏了进程中%list%
的值,并且它不能处理包含空格或感叹号的值。
@echo off & setlocal
set "list="The quick brown" "fox jumps over" "the lazy dog!!!""
set /a ubound = -1
for %%I in (%list%) do (
set /a ubound += 1
call set "arr[%%ubound%%]=%%~I"
)
rem // output results
set arr[
分裂的for
方法将正确地保持引用的空格。
发布于 2018-07-08 08:52:47
批处理只有一种类型的变量:字符串。
数组和列表是非常不同的东西(如果它们甚至在批处理中存在,但它们可以被模拟),这是讨论的。在批处理中,列表不是不同的元素,而是单个字符串,数组不是单个结构,而是不同的独立变量。
不过,可以使用for
循环将字符串(看起来像列表)拆分为分隔符(空格是默认的分隔符):
set list=a b c d
set element=2
for /f "tokens=%element%" %%a in ("%list%") do echo %%a
(注:这是批处理语法。若要在命令行上直接使用,请将每个%%a
替换为%a
)
https://stackoverflow.com/questions/51225079
复制相似问题