-1

I am currently having a problem. This one seemed to be pretty well covered but all the answers I found have not been working for me. What I want to do is this. I have a text file with multiple lines. I want to concat all of those to a string like

[LINE1]\n[LINE2]\n[LINE3]...

Now the answer for looping through the lines of a file I found were pretty understandable

for /F "delims=" %%i in (filename.key) do set content=%content% %%i

Now the problem is, that my batch file does loop through the file but %content% seems to be empty in every loop. So after all is done content just matches the last line of my file. What am I doing wrong?

double-beep
  • 5,031
  • 17
  • 33
  • 41
relief.melone
  • 3,042
  • 1
  • 28
  • 57
  • Batch simply doesn't support multi line strings. You can concatenate to a singe line string (even with embedded CRs but no LFs). –  Feb 12 '19 at 17:39
  • @LotPings that's exaclty what i am trying to do ;) – relief.melone Feb 12 '19 at 17:42
  • The `\n` in your sample line is misleading then, it has no special meaning - just text. –  Feb 12 '19 at 17:46

1 Answers1

1

You will need to modify your code to add delayed expansion to it:

@echo off
setlocal EnableDelayedExpansion

for /F "delims=" %%A in (filename.key) do set "content=!content! %%A"
rem Your other code here....:

But I would do it:

@echo off
SETLOCAL EnableDelayedExpansion

set "content="

for /F "delims=" %%A in (./config/git/read.key) do (
    if defined content (
        set "content=!content!\n%%A"
    ) else (
        set "content=%%A"
    )
)

echo %content%

rem Your other code here....:

You may select the way you want.

double-beep
  • 5,031
  • 17
  • 33
  • 41
  • You should probably explain the limitation of how long a line can be in a batch file. Once the `SET` command hits 8192 bytes it will truncate the data. – Squashman Feb 12 '19 at 17:21
  • Thanks. That almost works. The only thing is it devices the content by commas and even with the else statement i also get that delimiter at the beginning of the string. [edit] oh and I'm getting the last line twice[/edit] – relief.melone Feb 12 '19 at 17:25
  • ok i must have had a typo. for /f "delims=\n" %%i in (./config/git/read.key) do if defined content (set "content=!content!\n%%i") else (set content=%%i) works. will edit it in the answer and accept – relief.melone Feb 12 '19 at 17:37
  • 1
    FOR variables are case sensitive. You can't use an upper and lower case letter to reference the same token. – Squashman Feb 12 '19 at 17:55