如何在batch file中跳过&符号?

如何在batch file(或从Windows命令行)中跳过&符号,以便使用start命令在URL中使用&符号打开网页?

双引号在start不起作用; 这会启动一个新的命令行窗口。

更新1 :Wael Dalloul的解决scheme工作。 另外,如果在URL中有URL编码的字符(例如空格被编码为%20),并且它在batch file中,那么'%'必须被编码为'%%'。 在这个例子中情况并非如此。

例如,从命令行( CMD.EXE ):

 start http://www.google.com/search?client=opera&rls=en&q=escape+ampersand&sourceid=opera&ie=utf-8&oe=utf-8 

会导致

 http://www.google.com/search?client=opera 

在默认浏览器中打开,并在命令行窗口中显示这些错误:

 'rls' is not recognized as an internal or external command, operable program or batch file. 'q' is not recognized as an internal or external command, operable program or batch file. 'sourceid' is not recognized as an internal or external command, operable program or batch file. 'ie' is not recognized as an internal or external command, operable program or batch file. 'oe' is not recognized as an internal or external command, operable program or batch file. 

平台:Windows XP 64位SP2。

从cmd

  • &是这样逃跑的: ^& (基于@沃尔·达洛尔的回答 )
  • %不需要转义

一个例子:

 start http://www.google.com/search?client=opera^&rls=en^&q=escape+ampersand%20and%20percentage+in+cmd^&sourceid=opera^&ie=utf-8^&oe=utf-8 

从batch file

  • &是这样逃跑的: ^& (基于@沃尔·达洛尔的回答 )
  • %是这样转义的: %% (基于OP的更新)

一个例子:

 start http://www.google.com/search?client=opera^&rls=en^&q=escape+ampersand%%20and%%20percentage+in+batch+file^&sourceid=opera^&ie=utf-8^&oe=utf-8 

&用于分隔命令。 因此,您可以使用^来转义&

如果你提供了一个虚拟的第一个参数,你可以用引号括起来。

请注意,在这种情况下,您需要提供一个虚拟的第一个参数,因为start会将第一个参数视为新控制台窗口的标题(如果引用的话)。 所以下面的工作(在这里):

 start "" "http://www.google.com/search?client=opera&rls=en&q=escape+ampersand&sourceid=opera&ie=utf-8&oe=utf-8" 
 explorer "http://www.google.com/search?client=opera&rls=...." 

命令

 echo this ^& that 

按预期工作,输出

 this & that 

命令

 echo this ^& that > tmp 

也可以工作,写入string文件“tmp”。 但是,在一个pipe道之前

 echo this ^& that | clip 

^的解释完全不同。 它试图将两个命令的输出“echo this”和“that”写入pipe道。 回声将工作,那么“那个”会给出一个错误。 话

 echo this ^& echo that | clip 

将string“this”和“that”放在剪贴板上。

没有^:

 echo this & echo that | clip 

第一个回声将写入控制台,并且只有第二个回声的输出将被传送到剪辑(类似于“> tmp”redirect)。 所以,当输出被redirect时,^不会引用&而是使其在redirect之前而不是在之后被应用。

要pipe一个&,你必须引用两次

 echo this ^^^& that | clip 

如果你把string放在一个variables中

 set m=this ^& that 

然后

 set m 

会输出

 m=this & that 

但显而易见的

 echo %m% 

因为Windows替代variables之后失败,导致

 echo this & that 

它将这个parsing为一个新的命令并尝试执行“那个”。

在batch file中,您可以使用延迟扩展

 setlocal enableDelayedExpansion echo !m! 

要输出到一个pipe道,我们必须用^&replacevariables值中的所有&,我们可以用%VAR:FROM = TO%语法来完成:

 echo !m:^&=^^^&! | clip 

在命令行中,“cmd / v”启用延迟扩展:

 cmd /v /c echo !m! 

即使在写入pipe道时也是如此

 cmd /v /c echo !m! | clip 

简单。

如果你需要echo一个包含&符号的string不会有帮助,因为你也会在输出中看到它们。 在这种情况下for

 for %a in ("First & Last") do echo %~a 

…在批处理脚本中:

 for %%a in ("First & Last") do echo %%~a 

要么

 for %%a in ("%~1") do echo %%~a