batch echo pipe symbol causing unexpected behaviour

There are several special characters that generally must be escaped when used in Windows batch files. Here is a partial list: < > & | ^ %

The escape character is ^. So to get a literal |, you should do this:

echo ^|

When the special character is in a variable, it becomes a bit harder. But if you use special syntax, you can replace characters in a variable like this:

set X=A^|B

REM replace pipe character with underscore
set Y=%X:|=_%

echo %Y%
REM prints "A_B"

The question did not specify the OS. For unix:

escape it

echo \|

or wrap in quotes

echo "|"

You must escape the | character before you print the var. The following prints a|b

@echo off

set x=a^|b
echo %x:|=^|%

Tags:

Batch File