Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do i read a text file INCLUDING empty lines in batch?

I want to make it so that the empty lines are also outputted. For eg, this is my example.txt file.

Hello 

This is a text file. Hello World!

And my code to run it is,

for /f "delims=" %%a in (%cd%\example.txt) DO ( 
echo. %%a
)

But it doesnt show the empty lines and instead shows it like

Hello
This is a text file. Hello World!

How do I make it so it shows the empty line too? Thanks!

like image 605
Rahbab Chowdhury Avatar asked Sep 19 '25 06:09

Rahbab Chowdhury


1 Answers

FOR /F ignores empty lines, but you can use findstr to prefix each line with a line number, then there aren't empty lines anymore.

setlocal EnableDelayedExpansion
FOR /F "delims=" %%L in ('findstr /N "^" "%~dp0\example.txt"') DO (
   set "line=%%L"
   set "line=!line:*:=!" & rem Remove all characters to the first colon
   echo(!line!
)

The problem with delayed expansion is that it destroys all ! and ^ characters from your file.

Therefore, you could toggle the mode.

setlocal DisableDelayedExpansion
FOR /F "delims=" %%L in ('findstr /N "^" "%~dp0\example.txt"') DO (
   set "line=%%L"
   setlocal EnableDelayedExpansion
   set "line=!line:*:=!" & rem Remove all characters to the first colon
   echo(!line!
   endlocal
)
like image 197
jeb Avatar answered Sep 23 '25 13:09

jeb