Home > Software engineering >  Trying to echo/redirect/append a variable value that has & and spaces in it without the quotes messi
Trying to echo/redirect/append a variable value that has & and spaces in it without the quotes messi

Time:12-18

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?

CodePudding user response:

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

  • Related