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
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.
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.
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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With