Windows批处理字符串操作在循环中 [英] Windows batch string manipulation in loop

查看:411
本文介绍了Windows批处理字符串操作在循环中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在当前目录中创建目录01,02,03,...,11和12。但是由于一个未知的原因,我的填充函数的0不工作在一个for循环。

I'm trying to make the directories "01", "02", "03", ..., "11" and "12" in the current directory. But for an unknown reason my padding 'function' of "0" doesn't work within a for loop.

@Echo on
SET suffix=12
SET v=0%suffix%
SET v=%v:~-2%
echo %v%
pause

(SET suffix=12
SET v=0%suffix%
SET v=%v:~-2%
echo %v%)

pause

  FOR /L %%q IN (9,1,11) DO (
SET suffixb=%%q
SET w=0%suffixb%
SET w=%w:~-2%
echo %w%
  )
pause

推荐答案

在批处理文件中,每行或每行块(括号内的代码)被解析,执行,并且对下一行/块重复该过程。在解析阶段,所有变量读取都将被删除,并由代码开始执行之前的变量之前的值替换。如果变量在行/块内更改其值,则不能从同一行/块内部检索此更改的值,因为变量读取操作不存在。

In batch files, each line or block of lines (code inside parenthesis) is parsed, executed and the process repeated for the next line/block. During the parse phase, all variable reads are removed, being replaced with the value in the variable before the code starts to execute. If a variable changes its value inside the line/block, this changed value can not be retrieved from inside the same line/block as the variable read operation does not exist.

通常的解决方法是使用延迟扩展。启用后,您可以将语法从%var%更改为!var!解析器,读取操作必须延迟,直到使用该值的命令开始执行。

The usual way to solve it is to use delayed expansion. When enabled, you can change (where needed) the syntax from %var% to !var!, indicating to the parser that the read operation must be delayed until the command that uses the value starts to execute.

setlocal enabledelayedexpansion
for /l %%a in (101 1 112) do (
    set "name=%%a"
    md "!name:~-2!"
)

这篇关于Windows批处理字符串操作在循环中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆