Nested variable name using EnableDelayedExpansion

烈酒焚心 提交于 2020-01-03 02:43:05

问题


I am working on a script to get max lengths of each column, I'm trying to store lengths of max length in _c1...n vars. number of columns unknown.

I was able to get length for each column, create variables to store each with set _c!i! = !n!, n is the length but in order to set the max length for a particular column I need to compare current with max and use something like !_c!!i!! which doesn't work, any ideas how to refer a variable which part of it's name coming from another variable?

Thanks...


回答1:


I assume that you are using the delayed expansion character because you are working inside a set of brackets "()". Doing that makes your process harder. I know that method is easier to read, but it is harder to code for.

Inside brackets, I know of only one method to access a variable that was 'built' out of one or more variables. That is to use the call function to cause the assembled variable to 'activate'. This method works both inside and outside of brackets.

Here is a small example:

@echo off
setlocal enabledelayedexpansion
(
  set i=10
  set _c!i!=something
  :: below is equivalent to echo !_c10!
  call echo %%_c!i!%%
)
endlocal

Output:

something

You can do almost everything using a CALL in front of it that you can without it, though in XP or earlier you cannot call internal commands like if and can only call 'external' programs like FIND.EXE.

If you can work outside of a set of brackets by possibly using a call :label statement, you can simply access the variable like this:

@echo off
setlocal enabledelayedexpansion
set i=10
set _c!i!=something

:: The below 2 statements are equivalent to `echo %_c10%`
echo !_c%i%!
call echo %%_c!i!%%

endlocal

Output:

something
something



回答2:


The CALL technique suggested by James K will work, but it is relatively slow and can be unsafe, depending on the content of the variable.

The following looks more complicated, but it is significantly faster and more reliable:

for %%A in (!i!) do echo !_c%%A!



回答3:


In your case there could be a third solution be possible, if your variables contains only numbers.

@echo off
setlocal enabledelayedexpansion
(
  set i=10
  set _c!i!=4711

  set /a tmp=_c!i!
  echo !tmp!
)

This works, as SET /A can access the content of a variable without the nedd of explicitly expansion charaters.



来源:https://stackoverflow.com/questions/12150065/nested-variable-name-using-enabledelayedexpansion

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!