Vincent Ketelaars
Vincent Ketelaars

Reputation: 1109

Bat script read lines in file with spaces

I have a simple script that prints every line in a txt file. However, if that txt filename has any spaces, it will not be able to open the file. In order to fix this I tried putting spaces around it. This then is recognized as a string instead of a file. Any suggestions how I could read through a file with spaces?

@echo off
set filename="my file.txt"
for /f "tokens=*" %%A in (%filename%) do (
  echo line=%%A
)

Upvotes: 1

Views: 1159

Answers (1)

Magoo
Magoo

Reputation: 80023

@echo off
set filename="my file.txt"
for /f "USEBACKQtokens=*" %%A in (%filename%) do (
  echo line=%%A
)

or preferably

@echo off
set "filename=my file.txt"
for /f "USEBACKQtokens=*" %%A in ("%filename%") do (
  echo line=%%A
)

The USEBACKQ option changes how the quote type is interpreted by FOR /F

See for /? from the prompt for documentation.

The syntax SET "var=value" (where value may be empty) is used to ensure that any stray trailing spaces are NOT included in the value assigned. In this case, that's not relevant, but in the general case, batch can show sensitivity to the position of spaces. The overall scheme is to ensure the filename presented is quoted if it contains separators, and that requires the for/f is told that the "item in quotes" is a filename, not simply a string.

Upvotes: 2

Related Questions