简体   繁体   English

尝试回显/重定向/附加一个变量值,其中包含 & 和空格,而引号不会把事情搞砸

[英]Trying to echo/redirect/append a variable value that has & and spaces in it without the quotes messing things up

In a batch file, suppose %PageName% has the value:在批处理文件中,假设 %PageName% 的值为:

This & That

And %FolderName%:和 %FolderName%:

Stuff & Junk

I want to be able to echo the following line and append it to an HTML file.我希望能够回显以下行并将其附加到 HTML 文件。 The expanded or "rendered" form of the line would look like this inside of the HTML file:该行的扩展或“呈现”形式在 HTML 文件中看起来像这样:

<li> <a href="Stuff & Junk/This & That.html">This & That</a></li>

And of course in a perfect world, I could just type this in the batch file to produce this result:当然,在一个完美的世界中,我可以在批处理文件中输入这个来产生这个结果:

echo <li> <a href="Stuff & Junk/This & That.html">This & That</a></li> >> "Stuff & Junk/index.html"

But of course this isn't a perfect world, and having ampersands and spaces stored inside variables makes everything a billion times more of a headache.但当然,这不是一个完美的世界,将 & 符号和空格存储在变量中会使一切都令人头疼十亿倍。 I tried:我试过:

echo ^<li^> ^<a href="%FolderName%"/"%PageName%".html^>"%PageName%"^</a^>^</li^> >> "%FolderName%\index.html"

This appends the following text to the index.html file:这会将以下文本附加到 index.html 文件:

<li> <a href="Stuff & Junk"/"This & That".html>"This & That"</a></li>

...which is awful because the quotation marks screw up everything. ...这很糟糕,因为引号搞砸了一切。 But if I get rid of the quotes, I get syntax errors because of the ampersands that break the line up into multiple commands.但是,如果我去掉引号,就会出现语法错误,因为 & 符号将行分成多个命令。 I'm stuck between a rock and a hard place.我进退两难。 Is there a solution for this?有解决办法吗?

@ECHO Off
SETLOCAL
SET "pagename=This & That"
SET "foldername=Stuff & Junk"

FOR /f "delims=" %%e IN ("%pagename%") DO FOR /f "delims=" %%y IN ("%foldername%") DO ECHO ^<li^> ^<a href="%%y%%e.html"^>%%y^</a^>^</li^>

GOTO :EOF

The trick is to assign the awkward string to a metavariable ( %%e/%%y ) and echo the result before cmd has a chance to figure out what's going on...诀窍是将笨拙的字符串分配给元变量( %%e/%%y )并在cmd有机会弄清楚发生了什么之前echo显结果......

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM