DextrousDave
DextrousDave

Reputation: 6793

Set variable that contains multiple values each on a new line

I have a batch script containing multiple variables, and all the values of these variables I want to add to a new variable that will be used in an email body. Issue is that all my values write to a single line, I want each variable to be on its own line:

set EmailText=%var1% %var2% %var3% %var4%

The EmailText value is all on one line. I want the values of var1, var2 var3 and var4 to all be on its own line, which will load into an email application.

I tried using the ^ character, eg %var1%^%var2% but does not work.

using echo you can do it using ^ but I do not want to echo this, I want to store all the strings, each on its own line, in another variable that is used in an email application

Thanks

Upvotes: 1

Views: 3189

Answers (2)

Aacini
Aacini

Reputation: 67236

You need to insert a <LF> character in the definition of the variable and show its value using Delayed Expansion:

@echo off
setlocal EnableDelayedExpansion

set "var1=One"
set "var2=Two"
set "var3=Three"
set "var4=Four"

set ^"EmailText=%var1%^

%var2%^

%var3%^

%var4%^"

echo !EmailText!

Although it is possible to remove the empty lines between variable values in the definition, the required syntax is ugly and awkward...

EDIT: New version to fulfill the new requirement stated in a comment...

@echo off
setlocal EnableDelayedExpansion

for /F %%a in ('copy /Z "%~F0" NUL') do set "CR=%%a"

set "var1=One"
set "var2=Two"
REM set "var3=Three"
set "var4=Four"

set "EmailText="
for %%v in (var1 var2 var3 var4) do (
   if defined %%v set ^"EmailText=!EmailText!!%%v!!CR!^
%Do not remove this line%
^"
)

echo !EmailText!

Output:

One
Two
Four

Upvotes: 3

lit
lit

Reputation: 16256

The following script tests each variable to see if it has content and appends together the string. If a semicolon can appear in the text, then choose another character to use as the newline delimiter.

@echo off
setlocal EnableDelayedExpansion

set "var1=One"
set "var2=Two"
set "var3=Three"
set "var4=Four"

SET LF=^


REM Do not remove blank lines for LF.

set "EmailText="
IF NOT "%var1%" == "" (SET "EmailText=%EmailText%%var1%;")
IF NOT "%var2%" == "" (SET "EmailText=%EmailText%%var2%;")
IF NOT "%var3%" == "" (SET "EmailText=%EmailText%%var3%;")
IF NOT "%var4%" == "" (SET "EmailText=%EmailText%%var4%")

SET "EmailText=%EmailText:;=!LF!%"

echo !EmailText!
EXIT /B 0

Example run:

12:56:51.62  C:\src\t\emailtext
C:>emailtext.bat >t.txt

12:57:07.74  C:\src\t\emailtext
C:>type t.txt
One
Two
Three
Four

Upvotes: 1

Related Questions