Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assigning newline character to a variable in a batch script

Tags:

batch-file

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?

like image 872
Rahul Avatar asked Aug 26 '10 05:08

Rahul


Video Answer


1 Answers

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"
)
like image 128
jeb Avatar answered Sep 21 '22 06:09

jeb



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!