Multiline text file, how to put into an environment variable

后端 未结 2 581
野的像风
野的像风 2020-12-19 11:44

i have a file called file.txt which contains:

     this is line one ^
     this is line two ^
     this is the last line

how can i put that

2条回答
  •  独厮守ぢ
    2020-12-19 12:14

    You were almost there. You need to read each line of text and then append the line plus a line feed to the variable.

    FOR /F could be used, but it doesn't play well with delayed expansion if the content contains ! characters. It is also awkward to preserve blank lines and awkward to disable the EOL option.

    A simpler solution is to use SET /P to read the lines. The limitations with this technique are:

    1) It trims trailing control characters from each line

    2) The file must use Windows standard line terminators of carriage return, line feed. It will not work with Unix style line feed.

    3) It is limited to reading 1023 bytes per line (not including the line terminator characters)

    Bear in mind that an environment variable can only hold a little less than 8 kbytes of data. So you are limited to only loading a very small file into a variable with this technique.

    @echo off
    setlocal enableDelayedExpansion
    set LF=^
    
    
    :: Two blank lines above needed for definition of LF - do not remove
    set file="test.txt"
    set "var="
    for /f %%N in ('find /c /v "" ^<%file%') do set lineCnt=%%N
    <%file% (
      for /l %%N in (1 1 %lineCnt%) do (
        set "ln="
        set /p "ln="
        set "var=!var!!ln!!lf!"
      )
    )
    set var
    

提交回复
热议问题