Assigning newline character to a variable in a batch script

后端 未结 2 1942
梦如初夏
梦如初夏 2020-12-03 04:07

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         


        
2条回答
  •  心在旅途
    2020-12-03 04:38

    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=^
    
    
    

    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"
    )
    

提交回复
热议问题