如何使用“(")读取批处理文件的多行 [英] How to read multiple lines of a batch file using "("

查看:73
本文介绍了如何使用“(")读取批处理文件的多行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,很久以前,我真的很喜欢批处理文件.我要回到这一点,但是对于我一生来说,我找不到从文件中获取文本行的首选方式.

So, long time ago I was really into batch files. I'm coming back to that, but for the life of me I can't find my preferred way of getting lines of text from a file.

它是这样的:

(
set /p %var1%=
set /p %var2%=
)>textfile.txt

谢谢.

推荐答案

糟糕!:-)

您正在尝试从文件读取而不是写入文件.因此,您需要< ,而不是> .

You are trying to read from a file, not write to it. So you need <, not >.

此外,仅在扩展变量时使用百分号,而不是在定义变量时使用百分号.

Also, you only use percents when you are expanding the variable, not when you are defining it.

最后,您应该在读取之前明确取消定义任何先前的值,因为读取空行将保留所有现有的变量值.

Lastly, you should explicitly undefine any prior value before reading, because reading an empty line will preserve any existing variable value.

(
  set "var1="
  set /p "var1="
  set "var2="
  set /p "var2="
) <textfile.txt

正如rojo在他的评论中所述,如果您要读取任意数量的行,则最好使用数组概念.但是,您必须首先确定要读取的总行数.

As rojo stated in his comment, you may be better off using an array concept if you are reading an arbitrary number of lines. However, you must first determine the total number of lines to read.

@echo off
setlocal enableDelayedExpansion

:: Determine number of lines
for /f %%N in ('find /c /v "" <textfile.txt') do set "cnt=%%N"

:: Read the file into an array
<textfile.txt (
  for /l %%N in (1 1 %cnt%) do (
    set "str.%%N="
    set /p "str.%%N="
  )
)

:: Display the array values
for /l %%N in (1 1 %cnt%) do echo(!str.%%N!)

使用SET/P是将文件读入变量的最快方法,并且避免了FOR/F有关空行和损坏的问题(如果启用了延迟扩展).但是SET/P有其自身的局限性:

Using SET /P is the fastest way to read a file into variables, and it avoids issues with FOR /F regarding empty lines and ! being corrupted if delayed expansion is enabled. But SET /P has its own limitations:

  • 源文件中的行必须以\ r \ n终止(回车和换行)
  • 每行必须< = 1021字节长
  • 跟踪控制字符已从行中剥离

这篇关于如何使用“(")读取批处理文件的多行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆