Reading a text file line by line and saving it in an array using a script package

I want to read a text file and save each line in an array. When I used the code below, "echo% i%" prints 0 each time, and only the value of the array [0] is assigned. But in "set n =% i%", the value of n is assigned as the last incremental value of i. Also "@echo! Array [%% i]!" prints as an array [0]! instead of typing a value. Is there any syntax error in the code?

set /A i=0 for /F %%a in (C:\Users\Admin\Documents\url.txt) do ( set /A i+=1 echo %i% set array[%i%]=%%a ) set n=%i% for /L %%i in (0,1,%n%) do @echo !array[%%i]! 
+6
source share
4 answers

Here is a method that is sometimes useful and very similar to your code:

 @echo off set "file=C:\Users\Admin\Documents\url.txt" set /A i=0 for /F "usebackq delims=" %%a in ("%file%") do ( set /A i+=1 call echo %%i%% call set array[%%i%%]=%%a call set n=%%i%% ) for /L %%i in (1,1,%n%) do call echo %%array[%%i]%% 
+10
source
 @echo off &setlocal enabledelayedexpansion for /F "delims=" %%a in (C:\Users\Admin\Documents\url.txt) do ( set /A count+=1 set "array[!count!]=%%a" ) for /L %%i in (1,1,%count%) do echo !array[%%i]! 

Inside the code block, you need delayed expansion and !variables! .

+2
source

Read the description of set /? about binding runtime environments. When you use %i% inside for , it is pre-extended to for execution. Instead, you need to use !i! .

0
source
 @ECHO OFF SETLOCAL FOR /f "tokens=1*delims=:" %%i IN ('findstr /n /r "$" url.txt') DO SET max=%%i&SET array[%%i]=%%j FOR /l %%i IN (1,1,%max%) DO CALL ECHO(%%array[%%i]%% GOTO :EOF 

if the line does not start ":"

0
source

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


All Articles