【问题标题】:Can't print (echo) a specific array element in a batchscript无法打印(回显)批处理脚本中的特定数组元素
【发布时间】:2019-10-15 11:38:53
【问题描述】:

我在批处理脚本中定义列表,然后想在每个列表中打印一个特定元素,但得到一个“ECHO 已关闭”输出(如果它是空的)。

我尝试使用 FOR 循环遍历列表,效果很好。

这是我正在尝试运行的代码

@echo off

rem --------start of Define list--------
set clist= A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
set ilist= X Y Z A B C D E F G H I J K L M N O P Q R S T U V W 
set testl= 1 2 3 4
rem --------end of Define list--------

echo %clist[1]%
echo %ilist[1]%
echo %testl[1]%

预期输出:

B
Y
2

实际输出:

ECHO is off
ECHO is off
ECHO is off

【问题讨论】:

  • 空格分隔的列表不是数组。当cmd.exe 人们谈论“数组”时,他们通常是指创建多个变量。 var[0]var[1]var[2]
  • 批处理脚本中没有列表或数组的概念,只有普通的环境变量(如VAR);但它们有时被命名为数组元素(如VAR[0]VAR[1] 等),我通常称之为伪数组。在这个帖子上循环:Arrays, linked lists and other data structures in cmd.exe (batch) script

标签: batch-file cmd


【解决方案1】:

这是一个使用here 描述的方法的示例,用于创建类似变量的数组:

@Echo Off & SetLocal EnableDelayedExpansion

Rem ------- Start of define list -------
Set "clist=A B C D E F G H I J K L M N O P Q R S T U V W X Y Z"
Set "ilist=X Y Z A B C D E F G H I J K L M N O P Q R S T U V W" 
Set "testl=1 2 3 4"
Rem -------- End of define list --------

Rem ------- Start of array lists -------
Set "i=0"
Set "clist[!i!]=%clist: =" & Set /A i+=1 & Set "clist[!i!]=%"
Set "i=0"
Set "ilist[!i!]=%ilist: =" & Set /A i+=1 & Set "ilist[!i!]=%"
Set "i=0"
Set "testl[!i!]=%testl: ="& Set /A i+=1 & Set "testl[!i!]=%"
Set "i="
Rem -------- End of array lists --------

Rem ----- Start your commands here -----
Echo %clist[1]%
Echo %ilist[1]%
Echo %testl[1]%
Pause
Rem ------ End your commands here ------

EndLocal & GoTo :EOF

【讨论】:

    【解决方案2】:

    如果你真的打算模仿一个数组,那么它会类似于这个。

    @echo off
    setlocal EnableDelayedExpansion
    
    set "clist=A B C D E F G H I J K L M N O P Q R S T U V W X Y Z"
    set /a cnt=0
    for %%a in (%clist%) do (
       set "clist[!cnt!]=%%a"
       set /a cnt+=1
    )
    for /l %%i in (0,1,!cnt!) do echo( clist[%%i]=!clist[%%i]!
    

    您也可以单独回显变量。

    echo %clist[1]%`
    

    【讨论】:

      【解决方案3】:

      如果您的“数组”成员值始终是 1 个字符长,那么只需要一个带有子字符串操作的变量。

      @echo off
      
      rem --------start of Define list--------
      set "clist=ABCDEFGHIJKLMNOPQRSTUVWXYZ"
      set "ilist=XYZABCDEFGHIJKLMNOPQRSTUVW" 
      set "testl=1234"
      rem --------end of Define list--------
      
      echo %clist:~1,1%
      echo %ilist:~1,1%
      echo %testl:~1,1%
      
      rem Show all values in loop
      setlocal enableDelayedExpansion
      for /l %%N in (0 1 25) do (
        echo clist[%%N] = !clist:~%%N,1!
        echo ilist[%%N] = !ilist:~%%N,1!
        echo testl[%%N] = !testl:~%%N,1!
      )
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-06-23
        • 1970-01-01
        • 2019-04-18
        • 1970-01-01
        相关资源
        最近更新 更多