简体   繁体   中英

Windows batch string manipulation in loop

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.

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!"
)

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.

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