批次:从有其路径中空格的文件中读取行 [英] Batch : read lines from a file having spaces in its path

查看:67
本文介绍了批次:从有其路径中空格的文件中读取行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

要从一个文件中读取行,在批处理文件中,你做的:

  FOR / F %%一中(myfile.txt的)做(
    :: 做东西...

现在假设文件在 C:\\ Program Files文件\\ MyFolder文件

  FOR / F %%一中(C:\\ Program Files文件\\ MyFolder文件\\ myfile.txt的),做(
    回声%%一

结果:

  C:\\ Program Files文件\\ MyFolder文件\\ myfile.txt的

这似乎是间preT给定的路径作为一个字符串,从而 %% A 是给定的路径。

这个没什么到目前为止,我已经找到的文件中。
请帮助我的人之前,我拍我自己。


解决方案

当你键入 帮助您的文档会告诉你,如果你有一个路径做什么空格。


 对于包含空格的文件名,你需要引用的文件名与
双引号。为了也用双引号以这种方式,则
需要使用usebackq选项,否则双引号将
除preTED为定义要分析的字符串。


在默认情况下,的语法FOR / F 如下。

  FOR / F [选项] IN(文件集)%变量DO命令[命令参数]
FOR / F [选项]%IN(字符串)变量DO命令[命令参数]
FOR / F [选项] IN(命令)%变量DO命令[命令参数]

此语法显示为什么你的键入变通办法。因为单引号表示执行在它的输出类型命令和循环。当您添加有usebackq 选项,语法更改此:

  FOR / F [选项] IN(文件集)%变量DO命令[命令参数]
FOR / F [选项] IN('字符串')​​%变量DO命令[命令参数]
FOR / F [选项] IN%变量(`command`)DO命令[命令参数]

现在你双引号的文件的路径,单引号的文字字符串,并把反引号(重音符)命令周围执行。

所以,你要做到这一点:

  FOR / F有usebackq%%一中(C:\\ Program Files文件\\ MyFolder文件\\ myfile.txt的),做(
    回声%%一

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.

解决方案

The documentation you get when you type help for tells you what to do if you have a path with spaces.

For file names that contain spaces, you need to quote the filenames with
double quotes.  In order to use double quotes in this manner, you also
need to use the usebackq option, otherwise the double quotes will be
interpreted as defining a literal string to parse.

By default, the syntax of FOR /F is the following.

FOR /F ["options"] %variable IN (file-set) DO command [command-parameters]
FOR /F ["options"] %variable IN ("string") DO command [command-parameters]
FOR /F ["options"] %variable IN ('command') DO command [command-parameters]

This syntax shows why your type workaround works. Because the single quotes say to execute the type command and loop over its output. When you add the usebackq option, the syntax changes to this:

FOR /F ["options"] %variable IN (file-set) DO command [command-parameters]
FOR /F ["options"] %variable IN ('string') DO command [command-parameters]
FOR /F ["options"] %variable IN (`command`) DO command [command-parameters]

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:

for /f "usebackq" %%a in ("C:\Program Files\myfolder\myfile.txt") do (
    echo %%a
)

这篇关于批次:从有其路径中空格的文件中读取行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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