Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

enter image description here

like image 370
Reinard Avatar asked Mar 17 '23 21:03

Reinard


1 Answers

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!"
)
like image 189
MC ND Avatar answered Mar 22 '23 23:03

MC ND