简体   繁体   English

在Windows批处理脚本的for循环中获取子字符串

[英]Getting a substring in a for loop in Windows batch script

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. 我不确定在这里做错了什么,但是我正在尝试解析文件夹中的一些XML文件并获取每个文件名的子字符串。 Here's what I got in my .bat file: 这是我在.bat文件中得到的:

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
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. 如果我自己在命令行中运行substring命令,它可以正常工作。 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. 首先将%%f更改为%%I ,这将使其更易于阅读。

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. 还应避免替换变量和修饰符之间可能出现的混淆,例如,允许您使用%%a .. %%z%%A .. %%Z

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM