0

I have a batch file where I have a variable named t%num% and num is an integer and t%num%=#. I need to set another variable called q equal to the contents of t%num%. I tried set q=t%num% so that q would contain a #, but it did not work.

  • If you can show the code, it would be easier to debug.... –  Apr 29 '17 at 00:35
  • 1
    The concept you are using is called _array_. See [Arrays, linked lists and other structures in Batch](http://stackoverflow.com/questions/10166386/arrays-linked-lists-and-other-data-structures-in-cmd-exe-batch-script/10167990#10167990) – Aacini Apr 29 '17 at 00:49

2 Answers2

1
@ECHO OFF
SETLOCAL
SET num=5
SET t%num%=36
CALL SET q=%%t%num%%%
ECHO %q% %t5%

GOTO :EOF

Uses the idea that % escapes % so that the parser substitutes-in the value of num and the result is set q=%t5%

Magoo
  • 77,302
  • 8
  • 62
  • 84
  • it works, and I understand how the percent signs work, but what's the difference between set and call set? – Nicholas Spicer Apr 29 '17 at 02:09
  • `set` assigns the value of `%%` `t` `%num%` `%%` so will assign the literal value `%t5%`. `call set` evaluates the result hence the *contents* of `t5`. – Magoo Apr 29 '17 at 02:33
0

You can (ab)use delayed environment variable expansion for this purpose.

Let's say you have an environment variable t5 defined. The following batch script will assign the content of t5 to the variable q:

setlocal EnableDelayedExpansion
echo t5: %t5%
set num=5
set q=!t%num%!
echo q: %q%

However, be aware that enabling delayed environment variable expansion will make ! a special character not only in the batch script, but also inside the content of environment variables. Try setting the following content for t5 before executing the little script above:

set t5=Hello World!

You will notice that the exclamation mark at the end of "Hello World" simply disappears.

Or try this cheeky bit:

set t5=Guess what: !num!

Setting t5 like this and then executing the script, well... i leave it to you to find out what will happen :)