简体   繁体   English

使用批处理文件从文件中读取文本时出现问题

[英]Issue while reading the text from file using batch file

I'm trying to write one batch file which will read text from a text file and set to a variable. 我正在尝试编写一个批处理文件,该文件将从文本文件读取文本并将其设置为变量。

This is the text file. 这是文本文件。

out.txt out.txt

C:\Program Files (x86)\Windows NT\text1.txt
C:\Program Files (x86)\Windows NT\text2.txt
C:\Program Files (x86)\Windows NT\text3.txt
   3 file(s) copied. 

Here my doubt is I want to set C:\\Program Files (x86)\\Windows NT to a variable. 在这里,我的疑问是我要将C:\\ Program Files(x86)\\ Windows NT设置为变量。 I tried with the following command which will hold the complete text file. 我尝试使用以下命令来保存完整的文本文件。

FOR /f "delims=/" %%a IN (out.txt) DO echo %%a

Can anyone please tell me how can I read a particular string from the text file. 谁能告诉我如何从文本文件中读取特定的字符串。

Thanks In Advance. 提前致谢。

If I understand correctly, you want to get the full path of the files mentioned in out.txt , but without the filename. 如果我理解正确,则希望获取out.txt提到的文件的完整路径,但没有文件名。 This can be done using parameter extensions , like this: 这可以使用参数扩展来完成,如下所示:

FOR /f "delims=" %%a IN (out.txt) DO ECHO %%~dpa

In your example, it will output 在您的示例中,它将输出

C:\Program Files (x86)\Windows NT\
C:\Program Files (x86)\Windows NT\
C:\Program Files (x86)\Windows NT\

Update: To save only the result of the first line , use this: 更新:保存第一行的结果 ,请使用以下命令:

@ECHO OFF
FOR /f "delims=" %%a IN (out.txt) DO (
    SET path_in_first_line=%%~dpa
    GOTO skip
)
:skip
ECHO %path_in_first_line%

Splitting the line using the backslash as a delimiter 使用反斜杠作为分隔符来分割行

for /f "tokens=1-3 delims=\" %%a in (out.txt) do set "var=%%a\%%b\%%c"
echo %var%

Asking for the drive and path of the element in the line 询问行中元素的驱动和路径

for /f "delims=" %%a in (out.txt) do set "var=%%~dpa"
echo %var%

Of course, as the for command iterates over all the lines in the file, the var variable will only hold the value retrieved from the last line in the file. 当然,由于for命令遍历文件中的所有行,因此var变量将仅保存从文件的最后一行中检索到的值。

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

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