批处理:从路径中有空格的文件中读取行
要从批处理文件中的文件中读取行,您需要执行以下操作:
for /f %%a in (myfile.txt) do (
:: do stuff...
)
现在假设您的文件位于 C:\Program Files\myfolder
for /f %%a in ("C:\Program Files\myfolder\myfile.txt") do (
echo %%a
)
结果:
C:\Program Files\myfolder\myfile.txt
这似乎将给定路径解释为字符串,因此%%a
是您给定的路径。
到目前为止我找到的文档中没有任何关于此的信息。 在我开枪自杀之前,请有人帮助我。
To read lines from a file, in a batch file, you do :
for /f %%a in (myfile.txt) do (
:: do stuff...
)
Now suppose you file is in C:\Program Files\myfolder
for /f %%a in ("C:\Program Files\myfolder\myfile.txt") do (
echo %%a
)
Result :
C:\Program Files\myfolder\myfile.txt
This seems to interpret the given path as a string, and thus %%a
is your given path.
Nothing about this in the documentation I have found so far.
Please someone help me before I shoot myself.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
当您输入
help for
时获得的文档会告诉您如果路径中包含空格该怎么办。默认情况下,
FOR /F
的语法如下。此语法显示了您的
type
解决方法为何有效。因为单引号表示执行type
命令并循环其输出。添加usebackq
选项后,语法将更改为:现在,您将文件路径用双引号引起来,将文字字符串用单引号引起来,并在要执行的命令周围添加反引号(重音符号)。
所以你想这样做:
The documentation you get when you type
help for
tells you what to do if you have a path with spaces.By default, the syntax of
FOR /F
is the following.This syntax shows why your
type
workaround works. Because the single quotes say to execute thetype
command and loop over its output. When you add theusebackq
option, the syntax changes to this:Now you double quote paths to files, single-quote literal strings, and put backticks (grave accents) around commands to execute.
So you want to do this:
找到了。
甚至不要问我为什么会这样。
Found it.
Don't even ask me why that works.
只是分享以下代码,希望有人能受益。
下面的代码既采取了有空格的路径,而且如果读取的行有空格,也不会导致缺少空格后的字符问题;
FOR /f "tokens=* delims=," %%a in ('type "C:\Progrem File\My Program"') do (
回显%%a
)
Just sharing the below code, hoping that somebody will get benefited.
The below code take both the path having spaces and also if the read lines has spaces, it wont cause any issue of the characters after space is missing;
FOR /f "tokens=* delims=," %%a in ('type "C:\Progrem File\My Program"') do (
echo %%a
)