for-loopfilenames

Spaces in file name in MSDOS batch file


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?


Solution

  • 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