Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read lines with blank spaces from a file using batch

I'm trying to read each line from a text file using batch.

The lines inside the file has some blank spaces, so this is an example of the input:

This is the first line
This is the second line
...

I'm using the following source code

FOR /f %%a in ("%1") do (
    @echo %%a
)
goto:eof

The output is the follwing:

This
This
...

I have read the following entry in Stack Overflow but is doesn't solve my issue. Batch : read lines from a file having spaces in its path

like image 850
Daniel Peñalba Avatar asked Oct 22 '12 14:10

Daniel Peñalba


2 Answers

try this.

FOR /f "tokens=* delims=,"  %%a in ('type "%1"') do (
    @echo %%a
)
like image 155
Henry Gao Avatar answered Nov 02 '22 22:11

Henry Gao


Bali C and Henry Gao skirt around the issue.

Your code is terminating the value at the 1st space because FOR /F is designed to parse a string into delimited tokens. The default delimiters are space and tab. You can preserve the entire line by setting DELIMS to nothing.

for /f "usebackq delims=" %%a in ("%~1") do echo %%a

But there are still potential problems: The FOR /F loop skips empty lines, and also skips lines that begin with the EOL character (; by default).

The FOR command (especially the FOR /F variant) is a complicated beast. I recommend reading http://judago.webs.com/batchforloops.htm for a good summary of the nooks and crannies of the FOR command.

like image 6
dbenham Avatar answered Nov 02 '22 22:11

dbenham