简体   繁体   English

如何在Windows批处理文件中使用FOR获取文本文件中的路径变量?

[英]How to get a path variable in a text file by using FOR in a Windows batch file?

I try to retrieve a path in a text file identified by a tag. 我尝试在由标签标识的文本文件中检索路径。

I have a line like that in my text file: 我的文本文件中有这样一行:

"mypath":"C:\myfolder"

I need to retrieve the path corresponding to mypath tag. 我需要检索与mypath标记相对应的路径。

I tried this: 我尝试了这个:

for /f tokens^=2^,3^ delims^=^"^:^" %%a in ('type %mytextfile%^|find """mypath"""') do (  
    echo %%a 
    echo %%b
)

But it doesn't work, the result is: 但这不起作用,结果是:

mypath
C

So my problem probably comes from the colon character that is used in the delimiter and in the string I want to get. 因此,我的问题可能来自定界符和想要获取的字符串中使用的冒号字符。

Two points: First, just use quotes for the for options instead of escaping everything. 有两点:首先,只对for选项使用引号,而不要转义所有内容。 Second, you can add a * after a tokens option to imply that no more tokenizing should be done and the rest should be returned as a single token: 其次,您可以在tokens选项之后添加* ,以表示不再需要进行进一步的标记化,其余应作为单个标记返回:

for /f "tokens=1* delims=:" %%A in ('findstr /b /c:"""mypath""" %mytextfile%') do (
  echo %%~A
  echo %%~B
)

A few more things: 还有几件事:

  • There's no need for type when the command you're piping to can read files just fine. 当您通过管道传递的命令可以读取文件时,无需type任何内容。 :-) :-)
  • findstr /b matches the search string at the beginning of the line, as an added check that you've really got the correct line. findstr /b与该行开头的搜索字符串匹配,这是对您是否确实具有正确行的补充检查。
  • The ~ for printing the variables just eliminates the quotes around the text, so you don't have to deal with them anymore. 打印变量的~只是消除了文本周围的引号,因此您不必再处理它们了。

暂无
暂无

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

相关问题 文本文件:如何获取string1和string2的下一个实例之间的文本并将其设置为Batch变量? - Text file: How to get the text between string1 & next instance of string2 and set as Batch variable? 批处理文件:如何使用已存储在字符串中的变量名称来获取变量的值 - Batch file: How to get variable's value using variable's name already stored in a string 使用批处理用字符串和变量替换Xml文件中的文本行 - Replacing text line in Xml file with string and variable using batch 如何使用批处理脚本从文本文件捕获变量? - How do i capture a variable from a text file with a batch script? 如何使用批处理文件替换文本文件第二行中的字符串? - how to replace a string on the second line in a text file using a batch file? Windows批处理文件,用于在html文件中查找变量字符串 - Windows batch file to find variable string in a html file 如何逐行读取批处理文件中多余字符的文本文件? 允许限制行长。(Windows,批处理脚本) - How to read text file line by line which is excessing characters in batch file? Limiting the line length is allowed.(Windows, batch script) 如何在批处理文件中获取带有特殊字符的 substring? - How to get a substring with special characters in batch file? Windows-批处理文件字符串操作 - Windows - Batch File string manipulation 如何在bash脚本变量中转义文件路径 - how to escape file path in bash script variable
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM