arrayswindowsparsingbatch-file

How to parse text file to load arrays in batch script


If I have this text file keys.txt:

key1=val 1
key2=val 2
key3=val 3

I can use this script to load this script to load the values:

@echo off
setlocal

for /f "usebackq tokens=1* delims==" %%I in ("keys.txt") do (
    set "%%~I=%%~J"
)

set key

The output is:

key1=val 1
key2=val 2
key3=val 3

However, I'm trying to load the following list values with known names into arrays in batch script:

;files array
files=filename1
files=filename2
...
files=filename_n
;folders array 
folders=foldername1
folders=foldername2
... 
folders=foldername_n
;sources array 
sources=value1
sources=vakue2
... 
sources=vakue_n
;other key value pairs
do_copy=yes
messagePromot=Are you sure?

I want the batch script to create 3 arrays in batch script by parsing the text file above. The result arrays will be:

files[0]=filename1
files[1]=filename2
...
files[n]=filename_n

folders[0]=foldername1
folders[1]=foldername2
...
folders[n]=foldername_n

sources[0]=value1
sources[1]=value2
...
sources[n]=value_n

do_copy=yes
messagePrompt=Are you sure? 

Suppose the array variables are known or predictable, the how I can write the batch script to parse such text file?


Solution

  • @ECHO Off
    SETLOCAL ENABLEDELAYEDEXPANSION
    rem The following settings for the directory and filename are names
    rem that I use for testing and deliberately include spaces to make sure
    rem that the process works using such names. These will need to be changed to suit your situation.
    
    SET "sourcedir=u:\your files"
    SET "filename1=%sourcedir%\q77561414.txt"
    
    :: remove variables starting count_
    FOR  /F "delims==" %%e In ('set count_ 2^>Nul') DO SET "%%e="
    
    FOR /f "usebackqtokens=1*delims==" %%b IN ("%filename1%") DO (
     IF "%%c" neq "" (
      IF DEFINED count_%%b (SET /a count_%%b+=1) ELSE (SET /a count_%%b=0)
      SET "%%b[!count_%%b!]=%%c"
     )
    )
    SET count
    SET |FIND "["
    
    GOTO :EOF
    

    Note that if the filename does not contain separators like spaces, then both usebackq and the quotes around %filename1% can be omitted.

    You would need to change the value assigned to sourcedir to suit your circumstances. The listing uses a setting that suits my system.

    I used a file named q77561414.txt containing your data for my testing.

    Note use of DELAYEDEXPANSION to access the values of the count variables.

    You haven't said what to do with other key value pairs, so I've just processed them...

    counts start at 0.