批处理文件中的 for 循环 - 当文件名用双引号给出时失败 [英] For loop in batch file - fails when file names are given in double quotes

查看:69
本文介绍了批处理文件中的 for 循环 - 当文件名用双引号给出时失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一段用批处理文件编写的代码,它在使用输入的文件夹名称中查找预定义的文件.如果用户没有在双引号中输入文件夹名称,这可以正常工作.但是当他输入双引号时,批处理文件中的for循环部分失败了.

I've a piece of code written in batch file which looks for a predefined file in a use entered folder name. This works fine if the user doesn't enter the folder name in double quotes. But when he enters in double quotes, the for loop part in the batch file fails.

代码:

FOR /F "usebackq delims=, skip=4" %%I IN (%A%\A.txt) DO ECHO %%I

当 A 的值用双引号给出时,它会失败并出现错误 系统找不到文件 F:\KnoB"\A.txt

When the value for A is given in double quotes it fails with error The system cannot find the file F:\KnoB"\A.txt

推荐答案

您从哪里获得文件夹名称?如果你从命令行参数中得到它,那么改变你的

Where do you get the folder name from? If you get it from a command-line argument, then change your

set A=%1

set A=%~1

删除引号(如果存在).

which removes the quotes, if present.

如果您通过 set/p 从用户处读取数据,则使用

If you're reading from the user via set /p then use

set /P A=Folder?
for %%x in (%A%) do set A=%%~x

做同样的事情.

通常,如果您从某处获取仅使用一个百分比作为变量的值(例如参数或 for 循环),则只需使用 ~

Generally, if you're getting the value from somewhere that uses only a single percent for variables (e.g. arguments or for loops), then just use the ~ in there.

您还想用引号将 for 循环的参数括起来,这样带空格的文件夹名称就不会引起令人不快的意外:

You also want to surround the argument to your for loop in quotes, so that folder names with spaces don't cause unpleasant surprises:

FOR /F "usebackq delims=, skip=4" %%I IN ("%A%\A.txt") DO ECHO %%I

这篇关于批处理文件中的 for 循环 - 当文件名用双引号给出时失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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