1

Suppose I have a text file with following contents:

Hello
World
Abc

Now I want to read this in batch and copy them into a single variable. So my variable should contain:

var=Hello World Abc

What is possible work around for this? If I am trying I am either getting the first word or the last line word.

Thanks

saurav
  • 427
  • 4
  • 14
  • 1
    To read a file in a batch-file you need to use a `FOR /F` command. You can then use the `SET` command to assign the variable from the `FOR` command to your `VAR` variable. – Squashman Dec 18 '17 at 15:49
  • seems similar to https://stackoverflow.com/questions/3068929/how-to-read-file-contents-into-a-variable-in-a-batch-file – Bentaye Dec 18 '17 at 15:54
  • @Bentaye Yeah I have seen that, but not getting solution for my issue – saurav Dec 18 '17 at 16:10
  • @Squashman, I have tried that one. This : for /f "delims=" %%x in (group.txt) do set Build=%%x echo %Build% It is giving only last line in Build variable – saurav Dec 18 '17 at 16:15
  • Have you tried anything on your own? Please share your efforts... – aschipfl Dec 18 '17 at 16:30

2 Answers2

1

This seems to work. I have appended \n to each line in the read file. I'm not sure how you expect that behavior to actually work:

@echo off
SETLOCAL EnableDelayedExpansion
set "filecontents="
for /f "delims=" %%x in (input.txt) do (
    set filecontents=!filecontents!%%x\n
    )
echo %filecontents%
  • Hey thanks for this. I modified a bit to : set "filecontents=" for /f "delims=" %%x in (group.txt) do ( set "filecontents=!filecontents!%%x " ) echo %filecontents% And it worked!! Thanks a ton – saurav Dec 18 '17 at 16:39
  • Cool. I should have noted your example output just ignored linebreaks and left out the `\n` in my code. Glad you got it going. –  Dec 18 '17 at 16:41
0

To read the contents of a file in a batch file you can use a FOR /F command. You then use the SET command to assign a value to a variable. Also, you will need to utilized delayed expansion to reassign the existing variable to the original variable. A leading space will get assigned so the echo command is using a substring to remove it.

@echo off
setlocal EnableDelayedExpansion
for /f "delims=" %%G IN (file.txt) do set "var=!var! %%G"
echo %var:~1%
Squashman
  • 13,649
  • 5
  • 27
  • 36