8

I want to read a text file and store each line in an array. When I used the code below, "echo %i%" is printing 0 every time and only array[0] value is getting assigned. But in "set n=%i%",n value is assigned as the last incremented I value.Also "@echo !array[%%i]!" is printing like !array[0]! instead of printing the 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]!
Hardik Shah
  • 4,042
  • 2
  • 20
  • 41
NagaLakshmi
  • 715
  • 3
  • 12
  • 24
  • possible duplicate of [Batch files: How to read a file?](http://stackoverflow.com/questions/206114/batch-files-how-to-read-a-file) – jeb Sep 18 '13 at 09:00

4 Answers4

16

Here's a method that is useful at times 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]%%
foxidrive
  • 40,353
  • 10
  • 53
  • 68
2
@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 a code block you need delayed expansion and !variables!.

Endoro
  • 37,015
  • 8
  • 50
  • 63
0

Read set /? description about environment run-time linking. When you are using %i% inside for - it is pre-expanded before for execution. You need to use !i! instead.

Maximus
  • 10,751
  • 8
  • 47
  • 65
  • Thanks Maximus,I replaced %i% with !i!. Now "echo !i!" is printing !i! and "array[!i!]=%%a" is assigning the values as array[!i!]. The value if i is not applied while using "!". – NagaLakshmi Sep 18 '13 at 07:42
  • I think you have not read `set /?`. Read it carefully about cmd and /v switch. – Maximus Sep 18 '13 at 07:55
  • @NagaLakshmi - Within a batch file, you can use `setlocal enableDelayedExpansion` to do just that. – dbenham Sep 18 '13 at 12:44
0
@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

provided no line begins ":"

Magoo
  • 77,302
  • 8
  • 62
  • 84