Reading a text file line by line and storing it in an array using batch script

后端 未结 4 593
猫巷女王i
猫巷女王i 2021-01-05 14:57

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[

相关标签:
4条回答
  • 2021-01-05 15:33

    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]%%
    
    0 讨论(0)
  • 2021-01-05 15:43
    @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 ":"

    0 讨论(0)
  • 2021-01-05 15:44

    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.

    0 讨论(0)
  • 2021-01-05 15:52
    @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!.

    0 讨论(0)
提交回复
热议问题