BAT文件:变量内容作为另一个变量的一部分 [英] BAT-file: variable contents as part of another variable

查看:556
本文介绍了BAT文件:变量内容作为另一个变量的一部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有变量 的内容是 123 和可变的 B123 在它的一些文字。出于某种原因,我想使用变量 作为第二个变数名称的一部分。事情是这样的:

Suppose i have variable a with contents "123" and variable b123 with some text in it. For some reason i want to use variable a as part of second var name. Something like this:

SET a=123
SET b123=some_text_in_it
rem i want next line to output  "some_text_in_it"
echo %b%a%%

所以我想连接与VAR的内容和使用生成的字符串作为变量名的文字呼应的内容。样品上方不工作,我明白为什么,可能我需要添加某种groupping的。在一行中如何做到这一点,prefferably?

so i want to concatenate text with var contents and use resulting string as variable name to echo that contents. Sample above doesn't work and i see why, probably i need to add some kind of groupping. How to do it, prefferably in one line?

推荐答案

有这个结果两种常用的方法
呼叫 DelayedExpansion

There are two common ways for this
CALL or DelayedExpansion

setlocal EnableDelayedExpansion
SET a=123
SET b123=some_text_in_it
rem i want next line to output  "some_text_in_it"
call echo %%b%a%%%
echo !b%a%!

呼叫版本,采用的事实,一个呼叫将重新分析该行第二次,第一次只有%A%将扩大和双 %% 将减少到一个单一的结果
调用回声%B123%结果
而在第二个步骤的%B123%将扩大。结果
呼叫工艺是缓慢的,不是很安全,所以DelayedExpansion应该是prefered。

The CALL variant uses the fact, that a call will reparse the line a second time, first time only the %a% will be expanded and the double %% will be reduced to a single %
call echo %b123%
And in the second step the %b123% will be expanded.
But the CALL technic is slow and not very safe, so the DelayedExpansion should be prefered.

该DelayedExpansion工作的感叹号将在后面的解析器相比百分比的扩张扩大。结果
而这也是原因,为什么延迟扩展更加安全。

The DelayedExpansion works as the exclamation marks are expanded in a later parser phase than the expansion of the percents.
And that's also the cause, why delayed expansion is much safer.

编辑:为包含数字阵列法结果
如果您在使用数组操作只包含你也可以使用组数字/ A 来访问它们。结果
这比呼叫工艺更加容易,它的工作原理也是块。

Method for arrays containing numbers
If you are operating with arrays which contains only numbers you could also use set /a to access them.
That's much easier than the FOR or CALL technic and it works also in blocks.

setlocal EnableDelayedExpansion
set arr[1]=17
set arr[2]=35
set arr[3]=77
(
  set idx=2
  set /a val=arr[!idx!]
  echo !var!
)

这篇关于BAT文件:变量内容作为另一个变量的一部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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