Batch file. Read the path from the text file and save each instance as a new variable?

I am trying to read the contents of a text file and save any paths found on each line into its own variable. Each line has only 1 path, and each line has a different text (double quotation marks, number and tab).

Is it possible? I spent about 6 hours reading Bing and Google, trying to figure out if I could do this, and I did not find anything.

Here is a sample text file:

"LibraryFolders" { "1" "D:\\Steam Games" "2" "E:\\Steam Games" } 

The number of library directories and the path to the library folder will be different for each user computer.

0
source share
2 answers
 @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 called q27630202.txt containing your data for my testing.

+3
source

You know that the data file looks almost like JSON. Just for grins and giggles, I decided to load it into JScript, massage it into actual JSON, create a JScript object from it, and then output the values โ€‹โ€‹of the objects back to the batch version of the script. It is not as effective as Magoo's solution, but it was an entertaining exercise nonetheless.

 @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]); } 
+1
source

Source: https://habr.com/ru/post/956223/


All Articles