Package: Parse TXT Lines to Array

I have a desire to read lines from a TXT file into an Array structure for use in the batch file that I use (for reading in hard coded configuration items).

A few notes / suggestions:

  • .TXT file in the same directory as the .BAT file
  • Only two columns to parse, unknown number of rows
  • Col1 and Col2 data may contain spaces, but no special characters
  • The .TXT file format / delimiter may be convenient for this task: Example: Col1 | Col2

I'm just looking for a few pointers to get me started.

Thank!

Mark

+2
batch-file
May 22 '15 at 17:54
source share
1 answer

Simulation of a 2-dimensional array with a numerical estimate:

Content textfile.txt :

 var 1,val 1 var 2,val 2 var 3,val 3 

Contents of test.bat :

 @echo off setlocal enabledelayedexpansion set idx=0 for /f "usebackq tokens=1* delims=," %%I in ("textfile.txt") do ( set "var[!idx!][0]=%%~I" set "var[!idx!][1]=%%~J" set /a idx += 1 ) set var 

Result:

 var[0][0]=var 1 var[0][1]=val 1 var[1][0]=var 2 var[1][1]=val 2 var[2][0]=var 3 var[2][1]=val 3 



Or you could model associative arrays whose key-value pair format might make more sense if you are dealing with configuration data.

Associative array modeling:

Content textfile.txt :

 key 1=val 1 key 2=val 2 key 3=val 3 

Contents of test.bat :

 @echo off setlocal for /f "usebackq tokens=1* delims==" %%I in ("textfile.txt") do ( set "config[%%~I]=%%~J" ) set config 

Result:

 config[key 1]=val 1 config[key 2]=val 2 config[key 3]=val 3 
+3
May 22 '15 at 19:02
source share
β€” -



All Articles