简体   繁体   English

批处理如何读取文本文件

[英]Batch how to read a text file

I need to make a batch file that can read a text file and I am using windows 7 ultimate 32 bit 我需要制作一个可以读取文本文件的批处理文件,并且我正在使用Windows 7 Ultimate 32位

I am currently using this code: 我目前正在使用此代码:

@ECHO OFF
for /f "delims=" %%x in (test.txt) do set "Var=%%x"
ECHO %Var%
pause

But this only reads the first line and I need it to read the whole thing. 但这仅读取第一行,而我需要它来读取整个内容。 I need it to display the full text file. 我需要它来显示全文文件。

Try this: 尝试这个:

@ECHO OFF
SetLocal EnableDelayedExpansion

for /f "delims=" %%x in ('type test.txt') do ( 
    set "Var=%%x"
    ECHO !Var!
)
pause

You need to enclose the for loop with brackets if you are performing multiple commands inside the for loop. 您需要封闭for用方括号循环,如果你是里面的执行多个命令for循环。 Besides that, SetLocal EnableDelayedExpansion will helps to expand the variable at execution time rather than at parse time . 除此之外, SetLocal EnableDelayedExpansion将有助于在执行时而不是在解析时扩展变量

Hope this helps. 希望这可以帮助。

Actually, this should read the whole file and set Var to the last line. 实际上,这应该读取整个文件并将Var设置为最后一行。

If you need to process the whole file, you have several options: 如果需要处理整个文件,则有几种选择:

  1. If you just need to do something for every line, then just use a block instead of the set "Var=%%x" : 如果只需要为每一行做某事,则只需使用一个块而不是set "Var=%%x"

     for /f "delims=" %%x in (test.txt) do ( rem Do something with %%x ) 
  2. If you need the complete file line-by-line in memory, use a counter and emulate arrays with lots of variables: 如果您需要在内存中逐行显示完整的文件,请使用计数器并模拟包含许多变量的数组:

     setlocal enabledelayedexpansion set cnt=0 for /f "delims=" %%x in (test.txt) do ( set "ine[!cnt!]=%%x" set /a cnt+=1 ) set /a numlines=cnt-1 

    and afterwards you can just use a for /l loop to access them again. 然后,您可以使用for /l循环再次访问它们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM