Use package to save multi-line variable to file

I've tried the following:

@echo off
REM New line.
set LF=^& echo.
set multiline=multiple%LF%lines%LF%%LF%of%LF%text

echo %multiline%

echo %multiline% > text.txt

      

Keeps only the first line of text.

So, I suppose the only way to do this is to use a for loop?

+3


source to share


2 answers


Your code never tries to create a variable that contains multiple lines of text. Rather, you are trying to create a variable that contains multiple commands (macros) that, when executed, create multiple lines of text.

Here's a simple script that actually creates a variable with multiple lines and then writes the content to a file:

@echo off
setlocal enableDelayedExpansion

:: Create LF containing a line feed character
set ^"LF=^
%= This creates a Line Feed character =%
^"

set "multiline=multiple!LF!lines!LF!of!LF!text"
echo !multiline!
echo !multiline!>test.txt

      



You can read more about using line characters in variables in Explain How dos-batch newline works . The code I used looks different, but it works because I used %= undefined variable as comment =%

that expands to zero.

If you want each line to conform to the Windows carriage return / line feed end-of-line standard, then you also need to create a carriage return variable. There is a completely different hack for getting a carriage return.

@echo off
setlocal enableDelayedExpansion

:: Create LF containing a line feed character
set ^"LF=^
%= This creates a Line Feed character =%
^"

:: Create CR contain a carriage return character
for /f %%A in ('copy /Z "%~dpf0" nul') do set "CR=%%A"

:: Define a new line string
set "NL=!CR!!LF!

set "multiline=multiple!NL!lines!NL!of!NL!text"
echo !multiline!
echo !multiline!>test.txt

      

+4


source


Run script a pause

after the command set

- and be surprised;)

After that change it to:



@echo off
REM New line.
set LF=^& echo.
set "multiline=multiple%LF%lines%LF%%LF%of%LF%text"
echo %multiline%
(echo %multiline%) > text.txt
type text.txt

      

+5


source







All Articles