Question

I have a batch file that allows the user to enter a file. It enters and stores the file path correctly. But when I go to enter the file and do anything with it, (in my case just set line1 as the first line and print it), It can't find the filename because it has a space in there.

Here is the code.

@ECHO OFF
SET /p "infile=enter file"
Echo you're file is %infile%


setlocal enableextensions enabledelayedexpansion
FOR /f "usebackqdelims=" %%a IN ("%infile%") do (
set line1= %1
    goto :endfor
)
:endfor
echo %line1%

pause
endlocal

And here is what happens.

enter image description here

When trying to find the file, The system thinks that files name ends at "my" instead of the full "my text.txt" How could I deal with the space in the filename?

Was it helpful?

Solution

Your problem is not the space in the name of the file. Your problem is that you are typing the name of the file with quotes, quotes that are stored in the variable, and then placing aditional quotes in the for command.

SET /p "infile=enter file"
set "infile=%infile:"=%"
Echo you're file is %infile%

Ensure there are no aditional quotes in the filename and this error will not happen (or don't use quotes when typing the name of the file)

OTHER TIPS

In addition to MC_ND's answer:
In the original code this line should be set to %%a and not %1 (without the space too):

set line1= %1
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top