7

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

Ross Ridge
  • 38,414
  • 7
  • 81
  • 112
Daniel Peñalba
  • 30,507
  • 32
  • 137
  • 219
  • Assuming `%1` is your file name, then your posted code cannot work as you describe. Either you must be using the `"usebackq"` option, or else your IN() clause must not be quoted. – dbenham Oct 22 '12 at 15:40

3 Answers3

12

try this.

FOR /f "tokens=* delims=,"  %%a in ('type "%1"') do (
    @echo %%a
)
Henry Gao
  • 4,858
  • 1
  • 21
  • 21
6

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.

dbenham
  • 127,446
  • 28
  • 251
  • 390
2

You need to set your delimiter for where the batch reads up to on each line

FOR /f "delims=;" %%a in ("%1") do (
    @echo %%a
)

The default delimiter for the end of the line is a semi colon. Alternatively use a character that you are not likely to see in the file like ~ or ¬ or something.

Bali C
  • 30,582
  • 35
  • 123
  • 152
  • 1
    Why setting the delimiter to a strange value, why not simply setting it to nothing? – jeb Oct 22 '12 at 15:44
  • @jeb How do you set it to nothing? `"delims="` will set it to space as default won't it? – Bali C Oct 22 '12 at 15:46
  • No, like dbenham shows, `"delims="` set it to nothing, only EOL can't be set this way to an empty value, `"EOL="` will set EOL to a quote. But EOL can be empty by other ways – jeb Oct 22 '12 at 15:47