Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use batch to save multi-line variable into a file

Tags:

batch-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

It only saves the first line of the text.

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

like image 484
Axonn Avatar asked Dec 23 '22 19:12

Axonn


2 Answers

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
like image 138
dbenham Avatar answered Jan 24 '23 10:01

dbenham


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
like image 33
Stephan Avatar answered Jan 24 '23 09:01

Stephan