Title: File path and name with spaces in batch file for loop
Posted: Tue, 7th October 2008
Category: Batch Files
We get this question all the time from third party developers who
work with us. It's a must implement in any stable batch file. The
problem: We want to loop through a file where either the name or
path has a space in it. Why is this a problem? Ok, consider the
following lines of code:
@echo off
for /f "tokens=1-3* delims=," %%a in (%1) do (
echo Column 1: %%a, Column 2: %%b >> output.csv
)
If you save this snippet as "test.bat" and launch a command
prompt, navigate to where the batch file is located and type in
test.bat test.csv, all will work fine and an
"output.csv" file will be created.
Generally in production environments though, we don't want end
users to have to open up command prompts and type in
test.bat "c:\documents and settings\user\My Documents\My
CSV File.csv". Usually, we just ask them to drag the
source file onto the batch file.
If we do that with the above script, what will happen? Well, it's
a bit of a lottery! If the file that you are dragging is located
in c:\myfiles\mycsv.csv then you'll probably be alright but if
it's located in c:\documents and settings\user\desktop\my
csv.csv, the script is unlikely to work as expected.
Still though, why don't I just enclose the %1 in
quotes, that's how I would deal with the problem if a path I was
typing on the command line contained some space characters. Ok,
so now your code looks like this:
@echo off
for /f "tokens=1-3* delims=," %%a in ("%1") do (
echo Column 1: %%a, Column 2: %%b >> output.csv
)
Well, now it's going to interpret your input file as a literal
string so instead of parsing your input file, it will actually
attempt to tokenize the path and the name of your file.
The solution: The solution is to call a type command
in the in part of your for loop for example,
for /f "tokens1-3* delims=," %%a in ('type %1') do
(... This will work make your script work as expected. So
your code should look like the following:
@echo off
for /f "tokens=1-3* delims=," %%a in ('type %1') do (
echo Column 1: %%a, Column 2: %%b >> output.csv
)
That's it, your batch files will now be able to handle drag and
drops flawlessly even when the path to the file in question
contains spaces.
As with all articles on Celtic Productions, this article is
protected by international copyright laws. It may be linked to
(we are of course most grateful of links to our articles),
however, it may never be reproduced without the prior express
permission of its owners, Celtic Productions. The code contained
therein of course can be used freely