我知道:echo "blah blah" >file.txt
有效。
并且echo "" >file.txt
也有效。
但是,如果我想在文件中只回显一个"
(双引号),该怎么办呢。
echo ">file.txt
不起作用,是否可以在一行命令中执行此操作?
答案 0 :(得分:7)
Windows shell的转义字符为^
,因此:
echo ^" > file.txt
答案 1 :(得分:4)
报价不需要转义以回应它,但是即使没有收盘报价,第一次报价后出现的字符也会被视为报价,因此除非报价被转义,否则尾随重定向将无效。
将单引号的回显重定向到文件而不转义很简单 - 只需将重定向移到前面即可。
>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