-1

I have tried multiple things with a code like this.

@echo off
set %1%=A
set %2%=B
set %3%=C
set %4%=D
set %5%=E
set %6%=F
set %7%=G
set %8%=H
echo %1%%2%%3%%4%%5%%6%%7%%8%%9%

But kinda nothing worked, the output was this:

1%2%3%4%5%6%7%8

How do I get it to output ABCDEFGH?

  • When you set variables, you **do not** enclose them in percentage signs. –  May 14 '17 at 13:26

2 Answers2

2

Try with

@echo off
set _1=A
set _2=B
set _3=C
set _4=D
set _5=E
set _6=F
set _7=G
set _8=H
echo %_1%%_2%%_3%%_4%%_5%%_6%%_7%%_8%

Starting from the concept, your problem is that %n with n in the range 0..9 is handled by the batch parser as an command line argument to the batch file, not a variable expansion operation.

You can use number prefixed variable names, but then you will require to enable delayed expansion and change the variable expansion syntax from %varName% in to !varName! to be able to retrieve the value. It is easier not use number prefixed variables names.

The second problem is that the syntax %varName% is only used where the variable value needs to be retrieved. When you set the value, the syntax is set varName=varValue, or still better you can quote the operation as set "varName=varValue" to avoid problems with special characters and inclusion of unneeded ending spaces.

MC ND
  • 69,615
  • 8
  • 84
  • 126
0

Your question is not clear. The code below do exactly what you requested:

@echo off
set A=A
set B=B
set C=C
set D=D
set E=E
set F=F
set G=G
set H=H
echo %A%%B%%C%%D%%E%%F%%G%%H%

However, is likely that this obvious solution is not what you are looking for...

If you want to know if is there a way to "automatically" define a series of variables and process they all, then the solution is to use an array. You may read the description of the array concept in this Wikipedia article and a detailed explanation of array management in Batch files at this answer. For example:

@echo off
setlocal EnableDelayedExpansion

rem Create "a" array with all elements given:
set n=0
for %%a in (A B C D E F G H) do (
   set /A n=n+1
   set a[!n!]=%%a
)

rem Show the 8 elements of "a" array
echo %a[1]%%a[2]%%a[3]%%a[4]%%a[5]%%a[6]%%a[7]%%a[8]%

rem Join *all* the elements of "a" array in a single variable
set "all="
for /L %%i in (1,1,%n%) do set "all=!all!!a[%%i]!"

echo %all%

Note that the last example works correctly no matters how many elements have been defined in "a" array.

Although you may also write the array elements in a shorter way, ommiting the braquets: set "a1=A" & set "a2=B", etc, and then use echo %a1%%a2%..., you should remember that the use of braquets is a standard notation used in many other programming languages, so it is convenient to keep it.

Community
  • 1
  • 1
Aacini
  • 65,180
  • 12
  • 72
  • 108