简体   繁体   English

带空格的批处理路径变量-如何转义双引号?

[英]Batch path variable with space - how to escape the double quotes?

I'm setting a variable with this directory 我在此目录中设置了一个变量

C:\My dir\Sub dir\Folder with a lot of spaces\file.html

like this: 像这样:

SET location="C:\My dir\Sub dir\Folder with a lot of spaces\file.html"

The problem is, when I echo %location% it comes with both double quotes. 问题是,当我回显%location%它带有两个双引号。 I've tried to remove using this: 我尝试使用以下方法删除:

set location=%location:"=\"%

But it does not work. 但这行不通。 I've searched a lot and I can't find an easy and simple solution. 我搜索了很多东西,但找不到简单的解决方案。 I'm using Windows 8. 我正在使用Windows 8。

An easy and simple solution is to store the path without the quotes, like this: 一个简单的解决方案是存储不带引号的路径,如下所示:

SET "location=C:\My dir\Sub dir\Folder with a lot of spaces\file.html"

This way the value will be stored with no quotes and the SET statement will still be protected from the effect of certain special characters. 这样,该值将不带引号存储,并且SET语句仍将受到保护,免受某些特殊字符的影响。 You will then either enclose %location% in quotes or omit the quotes as required. 然后,您可以将%location%括在引号中,或者根据需要省略引号。 For instance, if you are using the value as an argument of some command, you will likely need to put the quotes around it: 例如,如果您使用值作为某些命令的参数,则可能需要在其周围加上引号:

somecommand "%location%" …
…

And if you just need to output the path, the quotes may be unnecessary – and it's easy to leave them out: 而且,如果只需要输出路径,则引号可能是不必要的,并且很容易省略它们:

ECHO Location: %location%

Note that if the path has characters with special meaning, like & , ECHOing the path without the quotes would cause such characters to be interpreted in % evaluation. 请注意,如果路径中包含具有特殊含义的字符(如& ,则在不带引号的情况下回显路径会导致此类字符在%求值中进行解释。 To avoid that, you could temporarily enable and use delayed expansion: 为避免这种情况,您可以临时启用并使用延迟扩展:

SETLOCAL EnableDelayedExpansion
ECHO Location: !location!
ENDLOCAL
…

使用set "location=C:\\My dir\\Sub dir\\Folder with a lot of spaces\\file.html"来保留空格,但不要使用双引号。

Don't use quotes in Set . 不要在Set使用引号。

Later when you use that variable you include quotes around it eg 稍后,当您使用该变量时,应在其周围加上引号,例如

type "%location%"

Also this removes quotes 这也会删除引号

set location=%location:"=%

Yours I think replaces quotes with a backslash and a quote, not very useful. 您认为我用反斜杠和引号代替了引号,不是很有用。

Why even put it into a variable? 为什么还要将其放入变量?

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM