简体   繁体   中英

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:

This & That

And %FolderName%:

Stuff & Junk

I want to be able to echo the following line and append it to an HTML file. The expanded or "rendered" form of the line would look like this inside of the HTML file:

<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:

<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...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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