Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read entire content of a text file in batch

Tags:

batch-file

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.

like image 876
Nabi Avatar asked Oct 11 '12 16:10

Nabi


People also ask

How do I read the contents of a batch file?

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 .

What does %% do in batch?

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.

What is @echo off in batch?

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.

What is %% K in batch file?

So %%k refers to the value of the 3rd token, which is what is returned.


2 Answers

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
like image 33
Jeff K Avatar answered Nov 12 '22 00:11

Jeff K


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
like image 154
jeb Avatar answered Nov 12 '22 00:11

jeb