How can I load the contents of a text file into a batch file variable?

145,292

Solution 1

Use for, something along the lines of:

set content=
for /f "delims=" %%i in ('filename') do set content=%content% %%i

Maybe you’ll have to do setlocal enabledelayedexpansion and/or use !content! rather than %content%. I can’t test, as I don’t have any MS Windows nearby (and I wish you the same :-).

The best batch-file-black-magic-reference I know of is at http://www.rsdn.ru/article/winshell/batanyca.xml. If you don’t know Russian, you still could make some use of the code snippets provided.

Solution 2

If your set command supports the /p switch, then you can pipe input that way.

set /p VAR1=<test.txt
set /? |find "/P"

The /P switch allows you to set the value of a variable to a line of input entered by the user. Displays the specified promptString before reading the line of input. The promptString can be empty.

This has the added benefit of working for un-registered file types (which the accepted answer does not).

Solution 3

You can use:

set content=
for /f "delims=" %%i in ('type text.txt') do set content=!content! %%i

Solution 4

To read in an entire multi-line file but retain newlines, you must reinsert them. The following (with '<...>' replaced with a path to my file) did the trick:

@echo OFF
SETLOCAL EnableDelayedExpansion
set N=^


REM These two empty lines are required
set CONTENT=
set FILE=<...>
for /f "delims=" %%x in ('type %FILE%') do set "CONTENT=!CONTENT!%%x!N!"
echo !CONTENT!

ENDLOCAL

You would likely want to do something else rather than echo the file contents.

Note that there is likely a limit to the amount of data that can be read this way so your mileage may vary.

Share:
145,292
Keng
Author by

Keng

Personal Achievables: Medical Note: I now have irreversible damage to my kidneys and liver after having used this site.

Updated on March 20, 2021

Comments

  • Keng
    Keng about 3 years

    I need to be able to load the entire contents of a text file and load it into a variable for further processing.

    How can I do that?


    Here's what I did thanks to Roman Odaisky's answer.

    SetLocal EnableDelayedExpansion
    set content=
    for /F "delims=" %%i in (test.txt) do set content=!content! %%i
    
    echo %content%
    EndLocal