windows 使用批处理脚本逐行读取文本文件并将其存储在数组中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18866089/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 10:53:32  来源:igfitidea点击:

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

windowsbatch-file

提问by NagaLakshmi

I want to read a text file and store each line in an array. When I used the code below, "echo %i%"is printing 0every time and only array[0]value is getting assigned. But in "set n=%i%",nvalue 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?

我想读取一个文本文件并将每一行存储在一个数组中。当我使用下面的代码时,每次都"echo %i%"在打印0并且只array[0]分配了值。但是在 中"set n=%i%"n值被分配为最后一个递增的 I值。"@echo !array[%%i]!"也是打印!array[0]!而不是打印值。代码中是否有任何语法错误?

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]!

回答by foxidrive

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]%%

回答by Endoro

@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 expansionand !variables!.

在您需要的代码块中delayed expansion!variables!

回答by Magoo

@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 ":"

如果没有行开始“:”

回答by Maximus

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

阅读set /?有关环境运行时链接的说明。当您在%i%内部使用时for- 它for执行前已预先展开。你需要!i!改用。