Reputation: 5
I'm trying to read the contents of a text file and store any paths found on each line into their own variable. There's just 1 path on each line and also on each line there's other text (double quotes, a number and a tab).
Is this even possible? I've spent around 6 hours scouring Bing and Google trying to find out if i can do this and i haven't found anything.
Here's an example of the text file:
"LibraryFolders"
{
"1" "D:\\Steam Games"
"2" "E:\\Steam Games"
}
The number of library folders listed and path of the library folder will be different for every user's computer.
Upvotes: 0
Views: 1564
Reputation: 24476
You know, that data file looks almost like JSON. Just for grins and giggles, I decided to load it into JScript, massage it into valid JSON, create a JScript object from it, then output the object values back into the batch script. It's not as efficient as Magoo's solution, but it was an entertaining exercise nevertheless.
@if (@a==@b) @end /* Harmless hybrid line that begins a JScript comment
@echo off
setlocal
set "JSON=json.txt"
for /f "delims=" %%I in ('cscript /nologo /e:JScript "%~f0" "%JSON%"') do (
rem :: If you want to do stuff with each path returned,
rem :: change "delims=" to "tokens=2 delims==" above.
rem :: Then for each iteration of the loop, %%I will
rem :: contain a path from the text file.
set "%%I"
)
:: display all variables beginning with LibraryFolders
set LibraryFolders
goto :EOF
:: end batch / begin JScript */
var fso = new ActiveXObject('scripting.filesystemobject'),
JSONfile = fso.OpenTextFile(WSH.Arguments(0), 1);
var JSON = JSONfile.ReadAll().split(/\r?\n/);
JSONfile.close();
// massage the data into valid JSON
for (var i=0; i<JSON.length; i++) {
if (!i) JSON[i] += ':';
else if (/^\s*(\"[^\"]+\"\s*){2}$/.test(JSON[i])) {
JSON[i] = JSON[i].replace(/\"\s+\"/, '": "') + ',';
}
}
JSON = JSON.join('').replace(/,\s*\}/, '}');
// create new object from now valid JSON text
eval('var obj = {' + JSON + '}');
// dump "var=val" out to be captured by batch for /f loop
for (var i in obj.LibraryFolders) {
WSH.Echo('LibraryFolders['+i+']=' + obj.LibraryFolders[i]);
}
Upvotes: 1
Reputation: 80211
@ECHO OFF
SETLOCAL
:: remove variables starting $
FOR /F "delims==" %%a In ('set $ 2^>Nul') DO SET "%%a="
FOR /f "tokens=1*" %%a IN (q27630202.txt) DO (
IF "%%~b" neq "" SET "$%%~a=%%~b"
)
SET $
GOTO :EOF
I used a file named q27630202.txt
containing your data for my testing.
Upvotes: 3