如果您的文件名包含空格,则通常在 Windows 命令 shell ( cmd.exe
) 上将其双引号。
dir "\Program Files"
这也适用于其他特殊字符,如
^&;,=
.但它不适用于百分号,因为它们可能是变量替换的一部分。例如,mkdir "%os%"
将创建一个名为
Windows_NT
的目录.要转义百分号,可以使用插入符号:mkdir ^%os^%
但不幸的是,插入符号在双引号中失去了意义:
mkdir "^%os^%"
创建一个名为
^%os^%
的目录.这是我到目前为止发现的(Windows 7 命令 shell ):
^
和 &
可以用插入符号或双引号转义。 ;
, ,
, =
, 空格只能用双引号转义。 %
只能用插入符号转义。 '`+-~_.!#$@()[]{}
显然不必在文件名中进行转义。 <>:"/\|?*
无论如何,文件名都是非法的。 这似乎使引用文件名的通用算法变得相当复杂。例如,创建一个名为
My favorite %OS%
的目录,你必须写:mkdir "My favorite "^%OS^%
问题 1:有没有更简单的方法来安全地引用空格和百分比字符?
问题2:字符是
'`+-~_.!#$@()[]{}
吗?真的可以安全使用而不逃逸吗?
最佳答案
人物^
和 &
可以用脱字符或双引号转义。
配管时还有一个额外的限制。
When a pipe is used, the expressions are parsed twice. First when the expression before the pipe is executed and a second time when the expression after the pipe is executed. So to escape any characters in the second expression double escaping is needed:
The line below will echo a single
&
character:break| echo ^^^&
人物
%
只能用插入符号转义。%
也可以通过加倍逃脱。The
%
character has a special meaning for command line parameters andFOR
parameters.To treat a percent as a regular character, double it:
%%
例如,要创建一个名为 My favorite %OS% 的目录,您必须编写:
mkdir "My favorite "^%OS^%
Question 1: Is there an easier way to safely quote space and percent characters?
使用
%%
而不是 %
与第二个 "
在你通常期望它的最后。C:\test\sub>dir
...
Directory of C:\test\sub
03/06/2015 14:40 <DIR> .
03/06/2015 14:40 <DIR> ..
0 File(s) 0 bytes
2 Dir(s) 82,207,772,672 bytes free
C:\test\sub>mkdir "My favorite %%OS%%"
C:\test\sub>dir
...
Directory of C:\test\sub
03/06/2015 14:40 <DIR> .
03/06/2015 14:40 <DIR> ..
03/06/2015 14:40 <DIR> My favorite %Windows_NT%
0 File(s) 0 bytes
3 Dir(s) 82,207,772,672 bytes free
Question 2: Are the characters '`+-~_.!#$@()[]{} really safe to use without escaping?
不,还有一些其他情况必须转义其中的一些,例如使用延迟变量扩展或使用
for /f
时。 .见 Escape Characters对于所有详细信息......特别是汇总表。
来源 Syntax : Escape Characters, Delimiters and Quotes和 Escape Characters .
进一步阅读
关于cmd - 如何在 Windows cmd.exe 中正确转义文件名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30620876/