Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Batch Write to Text File with <Angle Brackets>

Tags:

xml

batch-file

I am attempting to dynamically create a small XML file with a Batch Script, but am having issues writing lines that begin and end with angle brackets.

1) If I do something like:

set foo=^<bar^>
echo %foo% > test.txt

This results in

> was unexpected at this time.
echo <bar> > test.txt


2) If I surround the echo statment variable with quotes: echo "%foo%" > test.txt, it writes successfully to the text file. However it obviously includes the quotes which I can't have.


3) Then I thought "Well, it must just be the angle brackets at the beginning and end..." So I added a character before and after the angle brackets:

set foo=a^<bar^>a
echo %foo% > test.txt

This resulted in some weird output which looks like my brackets are being numbered, and then it's looking for a file?

echo a 0<bar 1>test.txt
The system cannot find the file specified.


I've written elementary batch scripts before, but feel like I'm in over my head here... Any help is appreciated!

like image 325
sǝɯɐſ Avatar asked Nov 21 '25 06:11

sǝɯɐſ


2 Answers

Try this:

setlocal ENABLEDELAYEDEXPANSION

set foo=^<bar^>
echo !foo! > test.txt

endlocal

Using delayed expansion, and replacing the % with ! causes it to evaluate it differently.

like image 194
James L. Avatar answered Nov 23 '25 01:11

James L.


If using a pipe you need:

set foo=^^^<bar^^^>
like image 26
Alex K. Avatar answered Nov 23 '25 00:11

Alex K.