1

This is the error I have when running my test.bat file:

C:\Users>test.bat

C:\Dir1 1\file.csv

The system cannot find the file C:\Dir1.

This is the test.bat file content:

@Echo off

set "source=C:\Dir1 1\filename.csv"

echo %source%

for /F "Delims=" %%g in (%source%) do (@echo %%g)

As you can see the space in directory name seems to be the issue. How do I fix this?

5
  • 1
    Add quotes (double quotes, not single quotes). Basic Windows practice: anything with spaces in it needs to be (fully) quoted. Commented Jul 8, 2024 at 2:09
  • There are double quotes there already: set "source=C:\Dir1 1\filename.csv" Commented Jul 8, 2024 at 2:12
  • 1
    put the quotes around just the part to the right of = , that is the file path. Commented Jul 8, 2024 at 2:14
  • 1
    @DaveS that won't work as expected, as that includes the double quotes in the value of source, which is not what OP likely wants - see answer below. Commented Jul 8, 2024 at 2:20
  • If I add another set of double quotes like : set "source="C:\Dir1 1\test1.csv"" this is what I get: C:\Users>d:\mytest.bat "C:\Dir1 1\test1.csv" C:\Dir1 1\test1.csv Commented Jul 8, 2024 at 2:25

1 Answer 1

1

You correctly quote the set statement:

set "source=C:\Dir1 1\filename.csv"

This sets source to be C:\Dir1 1\filename.csv, and the double quotes around the entire assignment ensure that the double quotes don't end up in the value of source, but still avoid including trailing spaces, etc. As evidenced by your echo statement:

echo %source%

Consider adding quotes here, to make it perfectly clear there is nothing untoward here.

Your issue is with the for statement:

for /F "Delims=" %%g in (%source%) do (@echo %%g)

This should be either:

for /F "usebackq delims=" %%g in (`type "%source%"`) do (@echo %%g)

Or:

for /F "usebackq delims=" %%g in ("%source%") do (@echo %%g)

The first one works, because the backticks are now interpreted as containing a command to execute, and the value of %source% is placed in double quotes, to ensure values with spaces are processed correctly by the type command, which just returns ("types") the lines of the file.

The second one works, because the double quotes directly around the value in parentheses indicate to for that this is a file to be processed line by line, and the filename can contain spaces without issues due to the quotes.

So, a corrected version:

@echo off
set "source=C:\Dir1 1\filename.csv"
echo "%source%"
for /F "usebackq delims=" %%g in ("%source%") do (@echo %%g)

A great source for details on these commands is here: https://ss64.com/nt/for_cmd.html

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.