Package: reading lines from a file that has spaces in its path

To read lines from a file in a batch file, follow these steps:

for /f %%a in (myfile.txt) do ( :: do stuff... ) 

Now suppose the file is located in C:\Program Files\myfolder

 for /f %%a in ("C:\Program Files\myfolder\myfile.txt") do ( echo %%a ) 

Result:

 C:\Program Files\myfolder\myfile.txt 

This seems to interpret the given path as a string, and thus %%a is your given path.

Nothing about this in the documentation I have found so far. Please help me before I shoot myself.

+6
command-line batch-file
source share
3 answers

The documentation that you get when you type help for tells you what to do if you have a path with spaces.

 For file names that contain spaces, you need to quote the filenames with double quotes. In order to use double quotes in this manner, you also need to use the usebackq option, otherwise the double quotes will be interpreted as defining a literal string to parse. 

The default FOR /F syntax is as follows.

 FOR /F ["options"] %variable IN (file-set) DO command [command-parameters] FOR /F ["options"] %variable IN ("string") DO command [command-parameters] FOR /F ["options"] %variable IN ('command') DO command [command-parameters] 

This syntax shows why the type workaround works. Because single quotes are said to execute the type command and loop through its output. When you add the usebackq parameter, the syntax changes to this:

 FOR /F ["options"] %variable IN (file-set) DO command [command-parameters] FOR /F ["options"] %variable IN ('string') DO command [command-parameters] FOR /F ["options"] %variable IN (`command`) DO command [command-parameters] 

Now you specify the file paths twice, literal strings with one quotation mark, and place reverse feedback signals (serious accents) around the commands that are executed.

So you want to do this:

 for /f "usebackq" %%a in ("C:\Program Files\myfolder\myfile.txt") do ( echo %%a ) 
+6
source share

Found.

 for /f %%a in ('type "C:\Program Files\myfolder\myfile.txt"') do ( echo Deleting: %%a ) 

Don't even ask me why this works.

+1
source share

Just share the code below, hoping that someone will benefit.

The code below uses a space, and if the reading lines have spaces, this will not cause problems with characters after the space,

FOR / f "tokens = * delims =," %% a in ('type "C: \ Progrem File \ My Program"') do (echo %% a)

0
source share

All Articles