How to handle space of Filename in Batch For Loop
Solution 1
I don't think you need to quote the paths, you can just use the short names in the expanded path. So use %~dps instead of %~dp
@echo off
echo processing please wait...
setlocal enabledelayedexpansion
set txtfile=%~dps0mysql\my.ini.bak
set newfile=%~dps0mysql\my.ini
if exist "%newfile%" del /f /q "%newfile%"
for /f "tokens=*" %%a in (%txtfile%) do (
set newline=%%a
echo !newline! >> %newfile%
)
By the way, the error I get with your original code is slightly different from your error, not sure why.
The system cannot find the file C:\Program.
Solution 2
The space in the path is indeed preventing FOR /F from opening the file successfully. You need quotes around the file name, but then you also need the FOR /F "USEBACKQ" option so that the quoted name is treated as a file name instead of a text string.
Using "TOKENS=*"
is almost, but not quite the same as "DELIMS="
"DELIMS="
preserves the entire line"TOKENS=*"
preserves the remainder of the line after first stripping any leading spaces and/or tabs
I generally prefer "DELIMS="
unless I have a reason to strip leading spaces.
If there is a chance that the .INI file can contain !
character then you will want to toggle delayed expansion on and off within the loop. The value of %%a
will be corrupted if it contains !
and delayed expansion is enabled.
It is more efficient to enclose the entire FOR loop within another set of parens and redirect the output just once instead of once for each iteration. It also eliminates the need to first delete the file if it already exists.
@echo off
echo processing please wait...
setlocal disableDelayedExpansion
set "txtfile=%~dp0mysql\my.ini.bak"
set "newfile=%~dp0mysql\my.ini"
>"%newfile%" (
for /f "usebackq delims=" %%a in ("%txtfile%") do (
set newline=%%a
setlocal enableDelayedExpansion
rem Presumably more processing goes here
echo !newline!
endlocal
)
)
Wasim A.
[email protected] | Skype:wasimxe | Whatsapp: +923455407008
Updated on June 08, 2022Comments
-
Wasim A. almost 2 years
@echo off echo processing please wait... setlocal enabledelayedexpansion set txtfile=%~dp0mysql\my.ini.bak set newfile=%~dp0mysql\my.ini if exist "%newfile%" del /f /q "%newfile%" for /f "tokens=*" %%a in (%txtfile%) do ( set newline=%%a echo !newline! >> %newfile% )
Now my.ini.bak file is in D:\Program Files\my.ini.bak
Error : The system cannot find the file Files\mysql\my.ini.bak.How to make this code work, so it copy each line from my.ini.bak to my.ini
-
Wasim A. over 11 yearsactually i have tried it but its not then coping each line from my.ini.bak to my.ini ... it copy the Full path of my.ini.bak file into my.ini
-
Gene over 11 yearsI just tried it. Works fine on my Windows 7 machine. I posted my version above.
-
dbenham about 10 yearsThis will not work on volumes where short names are disabled.
-
Synetech almost 8 yearsAlso, it will not work because you cannot always predict what the short filename will be.