I want to read entire content of a text file in a batch file. I found this :
for /f "delims=" %%x in (file.txt) do set content=%%x
but the "content" variable just has the last line, I want to read entire file into a single variable.
How to Use a BAT File. Using a BAT file in Windows is as simple as double-clicking or double-tapping it. You don't need to download any special program or tool. To use the first example from above, entering that text into a text file with a text editor and then saving the file with the .
Use double percent signs ( %% ) to carry out the for command within a batch file. Variables are case sensitive, and they must be represented with an alphabetical value such as %a, %b, or %c. Required. Specifies one or more files, directories, or text strings, or a range of values on which to run the command.
When echo is turned off, the command prompt doesn't appear in the Command Prompt window. To display the command prompt again, type echo on. To prevent all commands in a batch file (including the echo off command) from displaying on the screen, on the first line of the batch file type: Copy. @echo off.
So %%k refers to the value of the 3rd token, which is what is returned.
I'm not sure the exact format you are looking for in the 'content' variable, but this code should do the trick (The code simply sets content to blank, then loops through each line of file.txt and copies the line into content using delayed expansions):
@echo off
setlocal enabledelayedexpansion
set content=
for /f "delims=" %%x in (file.txt) do (set content=!content! %%x)
echo !content!
endlocal
From your comment
Is there any way to include lines in !content!
I assume you want linefeeds in your content variable, this can be done with an extra variable.
@echo off
setlocal EnableDelayedExpansion
set LF=^
rem ** The two empty lines are necessary
set "content="
for /f "delims=" %%x in (file.txt) do (
set "content=!content!%%x!LF!"
)
echo(!content!
endlocal
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