33

I'm trying to create a batch file which passes around a string with line feeds in it but its not working out. The continuation of the string is executed as a new command.

Is there anyway to encode a line feed or make this work?

2
  • 1
    Do you construct the multi-line value or read it from elsewhere? If the former; stackoverflow.com/questions/3294599/… Commented Aug 12, 2011 at 14:00
  • 5
    Don't confuse DOS with some command-interpreter in Windows. DOS is an OS. Commented Aug 27, 2011 at 10:25

2 Answers 2

43

You can create directly multiline strings with the caret (one empty line is required).

setlocal EnableDelayedExpansion
set multiLine=This is a ^

multiline text^

line3
echo !multiLine!

Or you can create first a newline character.

setlocal EnableDelayedExpansion
set LF=^


rem Two empty lines are required
set multiLine=This is a!LF!multiline text!LF!line3
echo !multiLine!

An explanation how this works can be found at Explain how dos-batch newline variable hack works

Sign up to request clarification or add additional context in comments.

3 Comments

Note that it seems to be necessary to use delayed expansion; this doesn't seem to work with regular variable expansion.
@jpmc26 Yes, for percent expansion you need the newline variable hack, as a linefeed normally stops the batch parser
@jeb Ah, I see. If you don't use delayed expansion, then the runtime expands the variable before interpreting the command, which results in a newline in the command. So it interprets the command as having ended at the newline. By using delayed expansion, the runtime doesn't expand the variable until after it interprets the command, so the newline doesn't affect how the runtime interprets it. Is that correct?
1

Expansion to jeb answer , Adding !LF!^ to each line would be easy

setlocal EnableDelayedExpansion
set LF=^



set multiLine=This is a!LF!^
multiline text!LF!^
line3
echo !multiLine! 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.