32

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?

Ross Ridge
  • 38,414
  • 7
  • 81
  • 112
chief7
  • 14,263
  • 14
  • 47
  • 80
  • 1
    Do you construct the multi-line value or read it from elsewhere? If the former; http://stackoverflow.com/questions/3294599/do-batch-files-support-multiline-variables – Alex K. Aug 12 '11 at 14:00
  • 5
    Don't confuse DOS with some command-interpreter in Windows. DOS is an OS. – user unknown Aug 27 '11 at 10:25

2 Answers2

41

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

Community
  • 1
  • 1
jeb
  • 78,592
  • 17
  • 171
  • 225
  • 1
    Note that it seems to be necessary to use delayed expansion; this doesn't seem to work with regular variable expansion. – jpmc26 Feb 05 '14 at 00:17
  • @jpmc26 Yes, for percent expansion you need the newline variable hack, as a linefeed normally stops the batch parser – jeb Mar 03 '14 at 07:33
  • 1
    @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? – jpmc26 Mar 03 '14 at 21:16
0

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! 
Smart Manoj
  • 5,230
  • 4
  • 34
  • 59