using batch echo with special characters

Batch FileCmdEscapingEcho

Batch File Problem Overview


This maybe really easy but there were no answers for it over the net. I want to echo a XML line via batch into a file but it misunderstands the XML closing tag for redirection ">". The line is as follows:

echo <?xml version="1.0" encoding="utf-8" ?> > myfile.xml

is there any way to give a hint to batch parser not to interpret a special string? I used double-quotes but it writes them to the file as well! The file should look like this after echo:

<?xml version="1.0" encoding="utf-8" ?>

Batch File Solutions


Solution 1 - Batch File

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 - Batch File

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. enter image description here

There is a short batch file, which prints a basic set of special character and their escape sequences.

Solution 3 - Batch File

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 - Batch File

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

Solution 5 - Batch File

The way to output > character is to prepend it with ^ escape character:

echo ^>

will print simply

>

Solution 6 - Batch File

The answer from Joey was not working for me. After executing

  echo ^<?xml version="1.0" encoding="utf-8" ?^> > myfile.xml

I got this error bash: syntax error near unexpected token `>'

This solution worked for me:

 echo "<?xml version=\"1.0\" encoding=\"utf-8\">" > myfile.txt

See also http://www.robvanderwoude.com/escapechars.php

Solution 7 - Batch File

Here's one more approach by using SET and FOR /F

@echo off

set "var=<?xml version="1.0" encoding="utf-8" ?>"

for /f "tokens=1* delims==" %%a in ('set var') do echo %%b

and you can beautify it like:

@echo off
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
set "print{[=for /f "tokens=1* delims==" %%a in ('set " & set "]}=') do echo %%b"
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::


set "xml_line.1=<?xml version="1.0" encoding="utf-8" ?>"
set "xml_line.2=<root>"
set "xml_line.3=</root>"

%print{[% xml_line %]}%

Solution 8 - Batch File

the escape character ^ also did not work for me. The single quotes worked for me (using ansible scripting)

shell: echo  '{{ jobid.content }}'

output:

 {
    "changed": true,
    "cmd": "echo  '<response status=\"success\" code=\"19\"><result><msg><line>query job enqueued with jobid 14447</line></msg><job>14447</job></result></response>'",
    "delta": "0:00:00.004943",
    "end": "2020-07-31 08:45:05.645672",
    "invocation": {
        "module_args": {
            "_raw_params": "echo  '<response status=\"success\" code=\"19\"><result><msg><line>query job enqueued with jobid 14447</line></msg><job>14447</job></result></response>'",
            "_uses_shell": true,
            "argv": null,
            "chdir": null,
            "creates": null,
            "executable": null,
            "removes": null,
            "stdin": null,
            "stdin_add_newline": true,
            "strip_empty_ends": true,
            "warn": true
        }
    },
    "rc": 0,
    "start": "2020-07-31 08:45:05.640729",
    "stderr": "",
    "stderr_lines": [],
    "stdout": "<response status=\"success\" code=\"19\"><result><msg><line>query job enqueued with jobid 14447</line></msg><job>14447</job></result></response>",
    "stdout_lines": [
        "<response status=\"success\" code=\"19\"><result><msg><line>query job enqueued with jobid 14447</line></msg><job>14447</job></result></response>"
    ]

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAmir ZadehView Question on Stackoverflow
Solution 1 - Batch FileJoeyView Answer on Stackoverflow
Solution 2 - Batch FileorbitcowboyView Answer on Stackoverflow
Solution 3 - Batch Filewalid2miView Answer on Stackoverflow
Solution 4 - Batch FilejebView Answer on Stackoverflow
Solution 5 - Batch FileAleks GView Answer on Stackoverflow
Solution 6 - Batch FileCompetoView Answer on Stackoverflow
Solution 7 - Batch FilenpocmakaView Answer on Stackoverflow
Solution 8 - Batch FilepriyankaView Answer on Stackoverflow