Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Batch: Parse TXT Lines into Array

Tags:

batch-file

I have a desire to read lines from a TXT file into an Array structure for use in a batch file I am using (to read in configuration elements currently hardcoded).

A few notes/assumptions:

  1. .TXT file in same directory as the .BAT file
  2. Only 2 columns to parse, unknown number of rows
  3. Col1 & Col2 data can contain spaces, but no special chars
  4. Format/delimiter of the .TXT file can be whatever is convenient to this task: Ex: Col1 | Col2

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

Thanks!

Mark

like image 317
Mark Pelletier Avatar asked May 22 '26 19:05

Mark Pelletier


1 Answers

Simulation of a 2-dimentional numerically-indexed array:

Contents of 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

Resulting output:

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 simulate associative arrays, whose key-value pair format might make more sense if you're dealing with configuration data.

Simulation of an associative array:

Contents of 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

Resulting output:

config[key 1]=val 1
config[key 2]=val 2
config[key 3]=val 3
like image 180
rojo Avatar answered May 26 '26 09:05

rojo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!