Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Batch File: FOR /F doesn't work if path has spaces

Tags:

batch-file

This is the problem I'm having:

@ECHO OFF

REM If this batch file is run in the same directory as "command.exe" then the
REM following line will work.
FOR /F "usebackq" %%A IN (`command.exe "C:\File Being Passed as a Parameter.txt"`) DO ECHO %%A

REM The following line does not work no matter where this batch file is run.
FOR /F "usebackq" %%A IN (`"C:\Folder With Spaces\command.exe" "C:\File Being Passed as a Parameter.txt"`) DO ECHO %%A

I would like to store this batch file wherever I want and not be forced to store it in the same folder as command.exe. Any suggestions?

like image 232
Rick Avatar asked Jun 24 '11 23:06

Rick


People also ask

How do you handle spaces in a batch file?

When you send arguments, those with poison or space characters need to be doublequoted. Inside your batch file, if you no longer need the surrounding doublequotes, you'd remove them by using %~5 instead of %5 . Additionally the recommended syntax for the set command is Set "VariableName=VariableValue" .

Can there be spaces in a file path?

Spaces are allowed in long filenames or paths, which can be up to 255 characters with NTFS.

What is %% f in batch file?

For simple batch files, a single character such as %%f will work. You can use multiple values for variable in complex batch files to distinguish different replaceable variables.

What does %1 mean in a batch file?

When used in a command line, script, or batch file, %1 is used to represent a variable or matched string. For example, in a Microsoft batch file, %1 can print what is entered after the batch file name.


2 Answers

Add CALL before the program name:

FOR /F "usebackq" %%A IN (`CALL "C:\Folder With Spaces\command.exe" "C:\File Being Passed as a Parameter.txt"`) DO ECHO %%A
like image 63
Andriy M Avatar answered Sep 21 '22 12:09

Andriy M


The call trick of Andriy M is clever and works fine, but I tried to understand the problem here.

This problem is caused by the cmd.exe, as you can read at cmd /help

....
the first and the last quote will be removed, when there are not exactly two quotes in the line.
...

So there is also another solution with simply adding two extra quotes

FOR /F "usebackq=" %%A IN (`""C:\Folder Space\myCmd.exe" "Param space""`) DO (
    ECHO %%A
)
like image 25
jeb Avatar answered Sep 25 '22 12:09

jeb