How do escape echo " for storing in a file?

2019-02-22 11:23发布

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

but, what if I want to echo only ONE " (double quote) in a file.

echo ">file.txt doesn't work, is it possible doing it in a one line command?

2条回答
▲ chillily
2楼-- · 2019-02-22 11:36

The escape character for the Windows shell is ^, so:

echo ^" > file.txt
查看更多
别忘想泡老子
3楼-- · 2019-02-22 11:38

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
查看更多
登录 后发表回答