Assigning newline character to a variable in a batch script

You can create a real newline character and assign it to a variable.

setlocal EnableDelayedExpansion
set LF=^


rem TWO empty lines are required
echo This text!LF!uses two lines

The newline best works with delayed expansion, you can also use it with the percent expansion, but then it’s a bit more complex.

set LF=^


rem TWO empty lines are required
echo This text^%LF%%LF%uses two lines
echo This also^

uses two lines

How it works?
The caret is an escape character, it escapes the next character and itself is removed.
But if the next character is a linefeed the linefeed is also removed and only the next character is effectivly escaped (even if this is also an linefeed).

Therefore, two empty lines are required, LF1 is ignored LF2 is escaped and LF3 is neccessary to finish the “line”.

set myLinefeed=^<LF1>
<LF2>
<LF3>

Hints:
It’s often better to use a quite different format of the newline variable definition,
to avoid an inadvertently deletion of the required empty lines.

(SET LF=^
%=this line is empty=%
)

I have removed to often one of the empty lines and then I searched forever why my program didn’t work anymore.

And the paranoid version checks also the newline variable for whitespaces or other garbage.

if "!LF!" NEQ "!LF:~0,1!" echo Error "Linefeed definition is defect, probably multiple invisble whitespaces at the line end in the definition of LF"

FOR /F "delims=" %%n in ("!LF!") do (
  echo Error "Linefeed definition is defect, probably invisble whitespaces at the line end in the definition of LF"
)

Leave a Comment