How to read all the contents of a text file in batch mode

I want to read the whole contents of a text file in a batch file. I found this:

for / f "delims =" %% x in (file.txt) do set content = %% x

but the variable "content" has only the last line, I want to read the entire file in one variable.

+4
source share
3 answers

From the comment

Is there any way to include strings in! content!

I assume that you want to use line feeds in your content variable, this can be done with an additional 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 
+4
source

I'm not sure which format you are looking for in the variable "content", but this code should do the trick (the code simply sets the content to empty and then iterates over each line of file.txt and copies line to content using delayed extensions):

 @echo off setlocal enabledelayedexpansion set content= for /f "delims=" %%x in (file.txt) do (set content=!content! %%x) echo !content! endlocal 
+2
source

In a modern copy of windows, you can also:

 powershell -Command cat "<file name>" 

The only HEADS UP:

 powershell YourScriptFile.ps1 

It will NOT be executed by default unless you change the system security settings ... as I found out when I tried to create the "cat" command. However, for one or two airliners like this, why bang your head against a wall when you can take advantage of this in most modern systems.

0
source

Source: https://habr.com/ru/post/1439217/


All Articles