如何在批处理文件中不循环的情况下打印数组中特定项目的值? [英] How to print value of a specific item in an array in batch file, without looping?

查看:93
本文介绍了如何在批处理文件中不循环的情况下打印数组中特定项目的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我查看了很多有关批处理数组的信息,但几乎所有信息都涉及遍历列表.有没有一种方法可以直接使用循环直接在特定索引 上打印值?

I looked at a lot of information about batch arrays, but pretty much all of it concerns iterating through the list. Is there a way to directly print a value at specific index without using a loop?

这是我正在尝试做的一个例子:

Here's an example of what I was trying to do:

@echo off
setlocal enabledelayedexpansion
set ITEM_LIST=(item1 item2 item3 item4 item5)

echo !ITEM_LIST[1]!
echo %ITEM_LIST[1]%

推荐答案

使用自扩展代码将字符串列表转换为数组变量

如果您既不想在获取值或构造数组时都进行迭代,则
您可以使用自我扩展代码.

Use self expanding code to turn a string list into an array variable

If you don't want to iterate neither on retrieving a value nor on building an array,
you can use self expanding code.

但是要当心在理解代码时会头疼.

But beware of getting headache when trying to understand the code.

@echo off & setlocal enabledelayedexpansion
Set i=0 & set "ITEM_LIST= item1 item2 item3 item4 item5"
Set "ITEM_LIST=%ITEM_LIST: ="&Set /a i+=1&Set "ITEM_LIST[!i!]=%"
Echo List has %i% entries
Set ITEM_LIST

echo !ITEM_LIST[1]!
echo %ITEM_LIST[5]%

样品运行:

> SO_45491838.cmd
List has 5 entries
ITEM_LIST[1]=item1
ITEM_LIST[2]=item2
ITEM_LIST[3]=item3
ITEM_LIST[4]=item4
ITEM_LIST[5]=item5
item1
item5


只需附加其他两个常见用途:


Just to append two other common uses:

@echo off & setlocal enabledelayedexpansion
Rem Set MonthName[01..12] to short English month names
Set i=100&Set "MonthName= Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec"
Set "MonthName=%MonthName: ="&Set /a i+=1&Set "MonthName[!i:~-2!]=%"
Set MonthName

Rem Set DayName[1..7] to short English day names
Set i=0&Set "DayName= Mon Tue Wed Thu Fri Sat Sun"
Set "DayName=%DayName: ="&Set /a i+=1&Set "DayName[!i!]=%"
Set DayName

这篇关于如何在批处理文件中不循环的情况下打印数组中特定项目的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆