Assigning newline character to a variable in a batch script
The following is the batch script i have written
@echo off
setlocal enabledelayedexpansion
set finalcontent=
For /F "tokens=1-2* delims= " %%I in (abc.txt) do (
IF %%J EQU MAJORVER (
set currentline=%%I %%J %1
set finalcontent=!finalcontent!!currentline!
) ELSE IF %%J EQU MINORVER (
set currentline=%%I %%J %2
set finalcontent=!finalcontent!!currentline!
) ELSE IF %%J EQU BUILDNUM (
set currentline=%%I %%J %3
set finalcontent=!finalcontent!!currentline!
) ELSE (
set currentline=%%I %%J %%K%NL%
set finalcontent=!finalcontent!!currentline!
)
)
echo %finalcontent%>>xyz.txt
I want a newline character appended at the end of every occurence of the variable currentline. Can anyone guide me on this?
You can create a real newline character and assign it to a variable.
setlocal EnableDelayedExpansion
set LF=^
rem TWO empty lines are required
echo This text!LF!uses two lines
The newline best works with delayed expansion, you can also use it with the percent expansion, but then it's a bit more complex.
set LF=^
rem TWO empty lines are required
echo This text^%LF%%LF%uses two lines
echo This also^
uses two lines
How it works?
The caret is an escape character, it escapes the next character and itself is removed.
But if the next character is a linefeed the linefeed is also removed and only the next character is effectivly escaped (even if this is also an linefeed).
Therefore, two empty lines are required, LF1 is ignored LF2 is escaped and LF3 is neccessary to finish the "line".
set myLinefeed=^<LF1>
<LF2>
<LF3>
Hints:
It's often better to use a quite different format of the newline variable definition,
to avoid an inadvertently deletion of the required empty lines.
(SET LF=^
%=this line is empty=%
)
I have removed to often one of the empty lines and then I searched forever why my program didn't work anymore.
And the paranoid version checks also the newline variable for whitespaces or other garbage.
if "!LF!" NEQ "!LF:~0,1!" echo Error "Linefeed definition is defect, probably multiple invisble whitespaces at the line end in the definition of LF"
FOR /F "delims=" %%n in ("!LF!") do (
echo Error "Linefeed definition is defect, probably invisble whitespaces at the line end in the definition of LF"
)
You can define the newline as follows:
set newline=^& echo.
Then, you can use the newline in the echo-statement, like this: (not applicable in the outlined situation, however)
echo %finalcontent%%newline%
or you can use the newline in each set-statement, like this: (mind the extra caret)
set finalcontent=!finalcontent!!currentline!^!newline!
or similarly:
set currentline=%%I %%J %1^%newline%