【发布时间】:2012-04-03 10:32:45
【问题描述】:
我知道:echo "blah blah" >file.txt 有效。
echo "" >file.txt 也可以。
但是,如果我只想在文件中回显一个 "(双引号)怎么办。
echo ">file.txt 不起作用,是否可以在一行命令中完成?
【问题讨论】:
标签: windows batch-file console cmd
我知道:echo "blah blah" >file.txt 有效。
echo "" >file.txt 也可以。
但是,如果我只想在文件中回显一个 "(双引号)怎么办。
echo ">file.txt 不起作用,是否可以在一行命令中完成?
【问题讨论】:
标签: windows batch-file console cmd
Windows shell 的转义字符是^,所以:
echo ^" > file.txt
【讨论】:
引号不需要转义来回显它,但是出现在第一个引号之后的字符将被视为引用,即使没有结束引号,所以尾随重定向将不起作用,除非引号被转义。
将单引号的回显重定向到文件而不转义很简单 - 只需将重定向移到前面。
>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",但"= 永远不能是变量