string 批处理文件:如何使用已存储在字符串中的变量名称获取变量值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19146651/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Batch file: How to get variable's value using variable's name already stored in a string
提问by user1596274
1) Quick example:
1)快速示例:
set a="Hello"
set d="a"
Now, how do I get the value of "a" using (the value of) variable d
? For example, the variable name could have been entered by a user using a prompt, or the name of the variable could have been sent to a function.
现在,如何使用(的值)变量获取“a”的值d
?例如,变量名称可能由用户使用提示输入,或者变量名称可能已发送到函数。
None of these ideas work:
这些想法都不起作用:
set e=%%d%%
set e=%%%d%%%
set e=set e=%%d%%
%e%
After an hour of brainstorming and Googling, I have come up with this, but it seems too complicated and clumsy - is there really no other/easier way?:
经过一个小时的头脑风暴和谷歌搜索,我想出了这个,但它似乎太复杂和笨拙——真的没有其他/更简单的方法吗?:
set a="Hello"
set b="Good day"
set c="Good night"
set /p d="Give me a variable name"
call :GetVarVal %%%d%%% "e"
REM This now gives the correct value:
echo %e%
goto :eof
:GetVarVal
set "%~2=%~1"
goto :eof
2) Also, sort of similar, is there a better way to do this (ideally without a custom function):
2)另外,有点类似,有没有更好的方法来做到这一点(理想情况下没有自定义函数):
set a="C:\Users\Blah\Documents\MP4Box\MP4Box.exe"
call :get_drive_and_path a
echo %b%
goto :eof
:get_drive_and_path
set b=%~dp1
goto :eof
Thanks!
谢谢!
回答by Endoro
example without delayed expansion
(preserves exclamation marks):
不带示例delayed expansion
(保留感叹号):
@echo off &setlocal
set "a=Hello!"
set "d=a"
call echo %%%d%%%
output:
输出:
Hello!
回答by pmod
回答by foxidrive
Part 2
第2部分
set file="C:\Users\Blah\Documents\MP4Box\MP4Box.exe"
for %%a in (%file%) do echo %%~dpa
回答by Chris
its just easy: as you type e.g.
很简单:当你输入例如
SET VarName=VarValue
Then the SET-function gets given a string looking like "VarName=VarValue" - it does not matter whether you use the marks there or not, the following commands do the same:
然后 SET 函数得到一个看起来像 "VarName=VarValue" 的字符串——你是否在那里使用标记并不重要,以下命令做同样的事情:
SET VarName=VarValue
SET "VarName=VarValue"
so now reflecting, what tools we have to build a string, we come up to the idea to use this:
所以现在反思,我们必须使用什么工具来构建字符串,我们想出了使用这个的想法:
SET "Name=VarName"
SET "%VarName%=VarValue"
Echo %Varname%
Better late than never - have a good time
迟到总比不到好 - 玩得开心