@echo off
for /f "tokens=1-3* delims=," %%a in (%1) do (
echo Column 1: %%a, Column 2: %%b >> output.csv
)
test.bat test.csv
, all will work fine and an "output.csv" file will be created.
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.