Multiline text file how to set environment variable

I have a file called file.txt that contains:

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

how can i put this in env var?

I can do this from a batch file: test.bat

    set LF=^
    [blank line]
    [blank line]
    rem two blank lines needed above
    set multi=Line 1!LF!Line 2!LF!Last line
    echo !multi!

three lines are output:

      Line 1
      Line 2
      Last line

so how can i get the .txt file in envvar inside the batch file?

+5
source share
2 answers

As dbham said, this can be done for / f as well, but it's a bit more complicated.

80% simple solution

setlocal EnableDelayedExpansion

set "var="
set LF=^


rem *** Two empty lines are required for the linefeed
FOR /F "delims=" %%a in (myFile.txt) do (
  set "var=!var!!LF!%%a"
)
echo !var!

But this fails:
- If the line is empty, it will be skipped
- If the line starts with ;, the EOL character - If the line contains !(and carriage)

But then you could use a more complex solution

@echo off
SETLOCAL DisableDelayedExpansion
set "all="
FOR /F "usebackq delims=" %%a in (`"findstr /n ^^ aux1.txt"`) do (
    set "line=%%a"
    SETLOCAL EnableDelayedExpansion
    set "line=!line:#=#S!"
    set "line=!line:*:=!"
    for /F "delims=" %%p in ("!all!#L!line!") do (
        ENDLOCAL
        set "all=%%p"
    )
)
SETLOCAL EnableDelayedExpansion
if defined all (
set "all=!all:~2!"
set ^"all=!all:#L=^

!"
set "all=!all:#S=#!"
)
echo !all!

?
-, findstr /n ^^ ,

1:My first Line
2:; beginning with a semicolon
3:
4:there was an empty line

, EOL ;.
, , , ! ^.

, (, delim : ).

# #S, , .
? , , FOR/F ,
linefeed ( #L), #L, # #S, .

/ endlocal, all line.
FOR/F-endlocal, %%p endlocal.

, , , all, .
#L , .
#S #.

, ...

+7
. , .

FOR/F , , !. EOL.

SET/P . :

1)

2) , . Unix.

3) 1023 ( )

, 8 . , .

@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
+2

All Articles