cmd - 如何在 Windows cmd.exe 中正确转义文件名?

标签 cmd escaping filenames

如果您的文件名包含空格,则通常在 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 and FOR 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 QuotesEscape Characters .

    进一步阅读
  • How does the Windows Command Interpreter (CMD.EXE) parse scripts?
  • 关于cmd - 如何在 Windows cmd.exe 中正确转义文件名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30620876/

    相关文章:

    javascript - 当我尝试在 Windows 中通过 cmd 执行代码时,我不断收到 "Path must be a string of buffer"错误

    powershell - CMD/MS-DOS 中的 ASCII 艺术

    powershell - 替换文件夹及其子文件夹中所有文件的文件名中的某些字符

    windows - 在 Windows 中,如何删除一个文本文件中存在于另一个文本文件中的所有行?

    JavaScript 控制台程序

    mysql - 用于插入的 joomla 转义文本

    检查 char 是否以\xHH 表示法写入

    java - 当我将其保存为字符串的一部分时,我希望停止将 < 在 Java 中转换为 <

    javascript - JavaScript 中的文件扩展名

    python - 处理从文件读取的文件名中的反斜杠转义