Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 
like image 550
Keng Avatar asked Sep 25 '08 15:09

Keng


People also ask

How do I convert a TXT file to a batch file?

Click File and then Save, and then navigate to where you want to save the file. For the file name, type test. bat and if your version of Windows has a Save as type option, choose All files, otherwise it saves as a text file. Once you have completed these steps, click the Save button and exit notepad.

Can a batch file read a text file?

Reading of files in a Batch Script is done via using the FOR loop command to go through each line which is defined in the file that needs to be read. Since there is a no direct command to read text from a file into a variable, the 'for' loop needs to be used to serve this purpose.

How do I append to a batch file?

Content writing to files is also done with the help of the double redirection filter >>. This filter can be used to append any output to a file. Following is a simple example of how to create a file using the redirection command to append data to files.


1 Answers

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).

like image 101
Will Bickford Avatar answered Sep 23 '22 21:09

Will Bickford