[英]Reading a text file line by line and storing it in an array using batch script
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. 当我使用下面的代码时,
"echo %i%"
每次都打印0
并且只分配了array[0]
值。 But in "set n=%i%"
, n
value is assigned as the last incremented I value.Also "@echo !array[%%i]!"
但是在
"set n=%i%"
, n
值被指定为最后一个递增的I值。还有"@echo !array[%%i]!"
is printing like !array[0]!
正在打印
!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]!
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]%%
@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!
在代码块中,您需要
delayed expansion
和!variables!
. 。
Read set /?
读
set /?
description about environment run-time linking. 有关环境运行时链接的说明。 When you are using
%i%
inside for
- it is pre-expanded before for
execution. 当您使用
%i%
里面for
-这是预发泡前 for
执行。 You need to use !i!
你需要使用
!i!
instead. 代替。
@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 ":" 没有线开始“:”
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.