How do escape echo " for storing in a file?

前端 未结 2 1324
Happy的楠姐
Happy的楠姐 2021-01-18 16:45

I know : echo \"blah blah\" >file.txt works. and that echo \"\" >file.txt works too.

but, what if I want to echo only ONE \"

2条回答
  •  难免孤独
    2021-01-18 17:12

    The quote does not need to be escaped to echo it, but characters appearing after the 1st quote will be considered quoted, even if there is no closing quote, so the trailing redirection will not work unless the quote is escaped.

    It is simple to redirect the echo of a single quote to a file without escaping - simply move the redirection to the front.

    >file.txt echo "
    

    The complete answer is a bit complex because the quote system is a state machine. If currently "off", then the next quote turns it "on" unless the quote is escaped as ^". Once the quote machine is "on", then the next quote will always turn it off - the off quote cannot be escaped.

    Here is a little demonstration

    @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(
    

    And here are the results

    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
    

    Addendum

    While it is not possible to escape a closing quote, it is possible to use delayed expansion to either hide the closing quote, or else counteract it with a phantom re-opening quote.

    @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
    

    results

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

提交回复
热议问题