Reading a text file in batch mode script

I have a text file, a.txt:

Hello world
Good afternoon.

I wrote a script package to read the contents of this file line by line:
FOR /F "tokens=* delims=" %%x in (a.txt) DO echo %%x

I get output as "Hello" "World" due to the default behavior of the delimiter (space). How can I override this behavior to get ouptut as "Hello World" "Good Afternoon"

+6
source share
1 answer

Your "for / f" code tokens = * delims = "%% x in (a.txt) do echo %% x" will work on most Windows operating systems unless you change the commands.

So, you can instead "cd" into the directory you want to read before executing the "for / f" command to follow the line. For example, if the file "a.txt" is located in the folder C: \ documents and settings \% USERNAME% \ desktop \ a.txt, you should use the following.

 cd "C:\documents and settings\%USERNAME%\desktop" for /f "tokens=* delims=" %%x in (a.txt) do echo %%x echo. echo. echo. pause >nul exit 

But since this does not work on your computer for a reason, there is an easier and more efficient way to do this. Using the "type" command.

 @echo off color a cls cd "C:\documents and settings\%USERNAME%\desktop" type a.txt echo. echo. pause >nul exit 

Or, if you want them to select a file from which to write to the package, you could do the following.

 @echo off :A color a cls echo Choose the file that you want to read. echo. echo. tree echo. echo. echo. set file= set /p file=File: cls echo Reading from %file% echo. type %file% echo. echo. echo. set re= set /p re=Y/N?: if %re%==Y goto :A if %re%==y goto :A exit 
+6
source

All Articles