8

I am trying to copy a list of files to a specific directory using a batch file. The first thing I need to do is to create a list of file names. I saw this this post Create list or arrays in Windows Batch. The following works fine. But I am not happy about the fact that it is in one line. As my list of files gets bigger and bigger, it becomes hard to read.

set FILE_LIST=( "file1.txt" "file2.txt" "file3.txt" )

And then I noticed this blog. It creates an array with multiple lines.

set FILE_LIST[0]="file1.txt"
set FILE_LIST[1]="file2.txt"
set FILE_LIST[2]="file3.txt"

I am wondering whether there is a way of creating a array as the following:

set FILE_LIST=( "file1.txt" 
     "file2.txt" 
     "file3.txt" )

so that I can separate the file names into multiple lines, while do not need to worry about the index.

Community
  • 1
  • 1
Yuchen
  • 30,852
  • 26
  • 164
  • 234

2 Answers2

10

In the same topic you refer to there is the equivalent of this solution (below "You may also create an array this way"):

setlocal EnableDelayedExpansion
set n=0
for %%a in ("file1.txt"
            "file2.txt"
            "file3.txt"
           ) do (
   set FILE_LIST[!n!]=%%a
   set /A n+=1
)
Aacini
  • 65,180
  • 12
  • 72
  • 108
  • why did you use `setlocal EnableDelayedExpansion`, I've read this answer:https://stackoverflow.com/a/6680005/4608491 , but I still don't understand why you use it. – 123iamking Apr 04 '18 at 04:20
  • @123iamking: The reason is explained in the [second topic linked](https://stackoverflow.com/questions/10166386/arrays-linked-lists-and-other-data-structures-in-cmd-exe-batch-script/10167990#10167990) in this question: "You must use `!index!` to store values in array elements when the index is changed inside a FOR or IF: `set elem[!index!]=New value`". The `setlocal EnableDelayedExpansion` command enables the use of `!delayed!` expansion. The `%standard%` expansion does _not_ update the variable value inside an IF or FOR command... – Aacini Apr 04 '18 at 15:22
  • @123iamking: Your linked answer just answers this question: "Are the two in fact separate commands and can be written on separate lines?". I suggest you to search and read more questions/answers on Delayed Expansion topic, like the answer _[below that one](https://stackoverflow.com/a/18464353/778560)_ that begins this way: "The existing answers don't explain it (sufficiently) IMHO"... – Aacini Apr 04 '18 at 16:57
3

Exactly repeat indents

set arr=(^
    "first name"^
    "second name"^
)

Check data

for %%a in %arr% do (
    echo %%a
)
Redee
  • 547
  • 5
  • 8
  • please consider explaining, it didn't work for me. – Mahi Feb 27 '23 at 18:23
  • Typed in *.bat file Setted array of strings and acces to cell of array from for loop iteration Go to console (cmd), then run *.bat file – Redee Mar 01 '23 at 02:19