5

I have a one line text file (it will always be just one line). For example:

helloworld.txt contains "hello world"

I want to read this into an environment variable via the command prompt.

so Set MyVar=somehow reads helloworld.txt

Does anyone know how to do this?

phuclv
  • 37,963
  • 15
  • 156
  • 475
Shai UI
  • 50,568
  • 73
  • 204
  • 309
  • Possible duplicate of ... http://stackoverflow.com/questions/3068929/how-to-read-file-contents-into-a-variable-in-a-batch-file – SteveC Nov 26 '14 at 12:13
  • [Windows cmd and MS-DOS are very different](https://superuser.com/q/451432/241386). There's neither `for /f` nor `set /P` in DOS, and of course there can't be such a long name as `helloworld.txt` – phuclv Feb 13 '20 at 00:40

2 Answers2

10
set /P VARNAME=<FILENAME.TXT

This will only work with first line and will handle everything up to the end of the line.

Found at http://ss64.com/nt/set.html

Jason Swager
  • 6,421
  • 6
  • 41
  • 56
7

This only works because you want the last line (or a one-line file).

for /f "delims=" %f in (helloworld.txt) DO Set MyVar=%f

For more information, use

for /?
agent-j
  • 27,335
  • 5
  • 52
  • 79
  • 2
    note that if you put this in a batch file use %% instead of % – Shai UI Jun 09 '11 at 19:11
  • this does not work for a sentence unfortunately, it only reads the first wrd – Shai UI Jun 28 '11 at 18:57
  • @foreyez, I changed the delimiter `for /f "delims=^" %f in (helloworld.txt) DO Set MyVar=%f`. This wouldn't work if the string had a `^` in it, but you can pick whatever character you want. – agent-j Jun 28 '11 at 19:03