I'm not sure what I'm doing wrong here, but I'm trying to parse through some XML files in my folder and get a substring of the each file name. Here's what I got in my .bat file:
for %%f in (*.xml) do (
echo %%f
echo %%f:~3,-4%%
)
The first echo prints out the file name just fine. But the second echo is what I'm having trouble with. I'm getting outputs like, say, for NewABCDEFG.xml:
NewABCDEFG.xml
NewABCDEFG.xml:~3,-4%
When I should be getting:
NewABCDEFG.xml
ABCDEFG
I can't figure out what's wrong. If I run the substring command in command line by itself, it works fine. Any suggestions?
Fixed it with the following script:
setlocal EnableDelayedExpansion
for %%f in (*.xml) do (
set filename=%%f
echo !filename:~7,-4!
)
The set line was what I really needed to get this to work, to expand environment variables at execution time, per the help guide.
First change %%f
to %%I
, that will make it easier read.
for %%I in (*.xml) do echo %%I & echo %%~nI
No need for delayed expansion in this case. My preference however is to avoid having multi-command line blocks:
for %%I in (*.xml) do call :DoIt %%I
exit /b
:DoIt
echo %1
echo %~n1
exit /b 0
Also avoid the possible confusion between replacement variable and the modifiers, allowing you to use %%a
.. %%z
or %%A
.. %%Z
for instance.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.