简体   繁体   English

在批处理脚本中使用文本文件中的数据

[英]Using data from text file in batch script

Batch contents: 批量内容:

FOR /F "tokens=1,*" %%i IN (list.txt) DO (
    cd "%%j"
    Echo %CD%
    pause
)

Execution run: 执行运行:

C:\Dwn>tmp1.bat

C:\Dwn>FOR /F "tokens=1,*" %i IN (list.txt) DO (
cd "%j"
 Echo C:\Dwn
 pause
)

C:\Dwn>(
cd "%APPDATA%\Microsoft\Windows\Start Menu\Programs\Administrative Tools"
 Echo C:\Dwn
 pause
)
The system cannot find the path specified.
C:\Dwn
Press any key to continue . . .

How come the system cannot find the path specified ? 为什么the system cannot find the path specified If I copy that cd command and execute it by itself it works fine. 如果我复制该cd命令并自行执行它可以正常工作。

It fails because the value of %%j contains %APPDATA%. 它失败,因为%% j的值包含%APPDATA%。 The value of %APPDATA% will not get expanded when you expand %%j because environment variable expansion occurs before FOR variable expansion. 扩展%% j时,%APPDATA%的值不会扩展,因为在FOR变量扩展之前发生环境变量扩展。

The fix is to use call cd "%%j" instead. 修复是使用call cd "%%j"代替。 The CALL will cause the command to go through an extra level of %VAR% expansion, which is exactly what you want. CALL将使命令经历额外的%VAR%扩展级别,这正是您想要的。

You also have a problem in that you use echo %CD% within the same DO code block. 您还遇到一个问题,即在同一个DO代码块中使用echo %CD% It will echo the value of the current directory before your change because the value of %CD% is expanded when the entire FOR statement is parsed. 它将在您更改之前回显当前目录的值,因为在解析整个FOR语句时会扩展%CD%的值。 You could fix this by using call echo %CD% , or by enabling delayed expansion with SETLOCAL EnableDelayedExpansion and using echo !CD! 您可以通过使用call echo %CD%或使用SETLOCAL EnableDelayedExpansion启用延迟扩展并使用echo !CD! . But the simplest fix is to simply use cd ; 但最简单的解决方法是简单地使用cd ; the CD command without any arguments will print the current directory to the screen. 没有任何参数的CD命令会将当前目录打印到屏幕上。

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

相关问题 如何使用批处理脚本从文本文件中获取唯一字符串 - how to get a unique string from a text file using Batch script 批处理脚本以重命名文本文件中的数据 - batch script to rename the data inside a text file 批处理脚本-从文本文件中提取值 - Batch Script - Pull values from text file 从文本文件复制文件的批处理脚本 - Batch Script to copy files from a Text file 如何使用批处理脚本将文本文件中的字符串写入 XML 文件? - How to write a string from a text file into an XML file using batch script? 使用批处理脚本在文本文件中的特定行号处插入文本 - Insert text at a particular line number in a text file using batch script 如何使用Windows批处理脚本搜索字符串并从文本文件中提取另一个字符串模式 - How to search a string and extract another string pattern from a text file using windows batch script 使用批处理脚本从文本文件中删除多行字符串 - Remove multi-line strings from a text file using a batch script 使用批处理脚本解析文本文件并从每行中删除前 2 个字符 - Parse a text file using batch script and remove the first 2 characters from each line 如何使用Windows批处理脚本在“,”中查找和替换文本文件中的“=”? - How to find and replace “=” in a text file with “,” using windows batch script?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM