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
It only saves the first line of the text.
So I suppose the only way to do this is using a for loop?
Your code never attempts to create a variable containing multiple lines of text. Rather you are attempting to create a variable that contains multiple commands (a macro) that when executed produces multiple lines of text.
Here is a simple script that truly 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 feed characters within variables at Explain how dos-batch newline variable hack works. The code I used looks different, but it works because I used an%= undefined variable as comment =%
that expands to nothing.
If you want each line to follow the Windows end of line standard of carriage return / line feed, then you need to also create a carriage return variable. There is a totally 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
Spend your script a pause
after the set
command - 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With