【问题标题】:How do escape echo " for storing in a file?如何转义 echo " 以存储在文件中?
【发布时间】:2012-04-03 10:32:45
【问题描述】:

我知道:echo "blah blah" >file.txt 有效。 echo "" >file.txt 也可以。

但是,如果我只想在文件中回显一个 "(双引号)怎么办。

echo ">file.txt 不起作用,是否可以在一行命令中完成?

【问题讨论】:

    标签: windows batch-file console cmd


    【解决方案1】:

    Windows shell 的转义字符是^,所以:

    echo ^" > file.txt
    

    【讨论】:

    • 不,我知道,但 ^ 字符仅适用于 ^\ ^& ^| ^> ^
    • 无论如何,我找到了自己的答案。 :D Setlocal EnableDelayedExpansion Set quote=" echo !quote!>file.txt 有了这个,我只需要这个: echo !quote!>file.txt 每次我需要它。
    • 哦,好吧,有趣...早些时候,在问这个问题之前它不起作用。也许我打错了。 :P 无论如何谢谢! :D
    【解决方案2】:

    引号不需要转义来回显它,但是出现在第一个引号之后的字符将被视为引用,即使没有结束引号,所以尾随重定向将不起作用,除非引号被转义。

    将单引号的回显重定向到文件而不转义很简单 - 只需将重定向移到前面。

    >file.txt echo "
    

    完整的答案有点复杂,因为报价系统是一个状态机。如果当前“关闭”,则下一个引用将其“打开”,除非引用转义为 ^"。一旦报价机“开启”,下一个报价将始终将其关闭 - 关闭的报价无法转义。

    这是一个小示范

    @echo off
    :: everything after 1st quote is quoted
    echo 1) "this & echo that & echo the other thing
    echo(
    
    :: the 2nd & is not quoted
    echo 2) "this & echo that" & echo the other thing
    echo(
    
    :: the first quote is escaped, so the 1st & is not quoted.
    :: the 2nd & is quoted
    echo 3) ^"this & echo that" & echo the other thing
    echo(
    
    :: the caret is quoted so it does not escape the 2nd quote
    echo 4) "this & echo that^" & echo the other thing
    echo(
    
    :: nothing is quoted
    echo 5) ^"this & echo that^" & echo the other thing
    echo(
    

    这是结果

    1) "this & echo that & echo the other thing
    
    2) "this & echo that"
    the other thing
    
    3) "this
    that" & echo the other thing
    
    4) "this & echo that^"
    the other thing
    
    5) "this
    that"
    the other thing
    

    附录

    虽然无法转义结束引号,但可以使用延迟扩展来隐藏结束引号,或者使用幻像重新开始引号来抵消它。

    @echo off
    setlocal enableDelayedExpansion
    
    :: Define a quote variable named Q. The closing quote is hidden from the
    :: quoting state machine, so everything is quoted.
    set Q="
    echo 6) "this & echo that!Q! & echo the other thing
    echo(
    
    :: The !"! variable does not exist, so it is stripped after all quoting
    :: has been determined. It functions as a phantom quote to counteract
    :: the closing quote, so everything is quoted.
    echo 7) "this & echo that"!"! & echo the other thing
    

    结果

    6) "this & echo that" & echo the other thing
    
    7) "this & echo that" & echo the other thing
    

    【讨论】:

    • 改用!"=! 更安全,因为" 可以是有效变量set ""=this is a quote",但"= 永远不能是变量
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-10-24
    • 1970-01-01
    • 2019-01-06
    • 2022-08-21
    • 1970-01-01
    • 2022-01-24
    • 2016-05-21
    相关资源
    最近更新 更多