0

In my batch file, I have some lines:

set "line1=bla"
set "line2=what"

I want to know how to put a variable onto the end of a static string to equal a defined variable name. So, canum is the line number. The variable %line1% exists, but in order to loop the above code above so I could have as many lines as I wanted written into a file, I would have the line number as a variable that increases every time it loops, then checks if the variable combined with line exists. It's hard to explain.

So basically, I would start out with some variables that, well vary in being defined or not. line1 could be defined, but could not. I would want to have one variable that is a number that increases by one every time the batch file loops that acts as the 1 in line1 or the 2 in line2. That number increases every time the batch file loops. First, the batch file checks if the nth line is defined, and if it is, to echo it into a file as an additional line using echo %lineNUM%>>file.txt (with NUM being the nth number). However, I don't know how to combine one static string (which, in my case is test and a variable (which, in my case is %canum%) to make one variable name that is defined.

:writeloop_setuplogical
set /a canum = %canum% + 1
if NOT defined !line%canum%! :done
echo !line%canum%!>>file.txt

This is my best take of what I just tried to explain. This makes my brain hurt.

oh no
  • 118
  • 6
  • 1
    [Arrays-linked-lists-and-other-data-structures-in-cmd-exe-batch-script](https://stackoverflow.com/questions/10166386/arrays-linked-lists-and-other-data-structures-in-cmd-exe-batch-script/10167990#10167990) – Aacini May 05 '20 at 02:54

1 Answers1

1

A couple of points: ditch the self reference in the set /A, all you need is Set /A canum+=1. Accessing arrays in batch requires the index variable to be expanded with delayed expansion within code blocks (parentheses). For /L loops are used to do this, as the 'combined' variable is able to be expanded with the for loops variable - !expansion [%%i]!

To prevent erroneous output, Redirection syntax should really be:

>>File.txt Echo !Line%Canum%!

Conditional testing can be used to ensure only variables containing defined values are appended to the file.

If Not "!Line%Canum%!" == "" >>File.txt Echo !Line%Canum%!

To execute within a code block:

  • Current value

    For %%i in (!Canum!) Do If Not "!Line%%i!" == "" >>File.txt Echo !Line%%i!

  • All values

    For /L %%i in (1,1,!Canum!) Do If Not "!Line%%i!" == "" >>File.txt Echo !Line%%i!

T3RR0R
  • 2,747
  • 3
  • 10
  • 25