using batch echo with special characters
Solution 1:
You can escape shell metacharacters with ^
:
echo ^<?xml version="1.0" encoding="utf-8" ?^> > myfile.xml
Note that since echo
is a shell built-in it doesn't follow the usual conventions regarding quoting, so just quoting the argument will output the quotes instead of removing them.
Solution 2:
In order to use special characters, such as '>' on Windows with echo, you need to place a special escape character before it.
For instance
echo A->B
will not work since '>' has to be escaped by '^':
echo A-^>B
See also escape sequences.
There is a short batch file, which prints a basic set of special character and their escape sequences.
Solution 3:
another method:
@echo off
for /f "useback delims=" %%_ in (%0) do (
if "%%_"=="___ATAD___" set $=
if defined $ echo(%%_
if "%%_"=="___DATA___" set $=1
)
pause
goto :eof
___DATA___
<?xml version="1.0" encoding="utf-8" ?>
<root>
<data id="1">
hello world
</data>
</root>
___ATAD___
rem #
rem #
Solution 4:
One easy solution is to use delayed expansion, as this doesn't change any special characters.
set "line=<?xml version="1.0" encoding="utf-8" ?>"
setlocal EnableDelayedExpansion
(
echo !line!
) > myfile.xml
EDIT : Another solution is to use a disappearing quote.
This technic uses a quotation mark to quote the special characters
@echo off
setlocal EnableDelayedExpansion
set ""="
echo !"!<?xml version="1.0" encoding="utf-8" ?>
The trick works, as in the special characters phase the leading quotation mark in !"!
will preserve the rest of the line (if there aren't other quotes).
And in the delayed expansion phase the !"!
will replaced with the content of the variable "
(a single quote is a legal name!).
If you are working with disabled delayed expansion, you could use a FOR /F
loop instead.
for /f %%^" in ("""") do echo(%%~" <?xml version="1.0" encoding="utf-8" ?>
But as the seems to be a bit annoying you could also build a macro.
set "print=for /f %%^" in ("""") do echo(%%~""
%print%<?xml version="1.0" encoding="utf-8" ?>
%print% Special characters like &|<>^ works now without escaping