Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

For /L loop with padded number

I wish to make a nested for loop in order to process some files. I have looked extensively for the solution, and have found many similar versions, but since this is my first time I am having trouble combining methods to do what I want.

Basically - I want a FOR /L loop that cycles through a range of padded numbers from 001 to say 500.

I know I can specify a range (1,1,500), but obviously not as (001,001,500). How can I add the 00, and then subsequently when %%a is >9, just a 0? I imagine this is as a sting but perhaps there is another way?

My code as I wished it to be (obviously wrong):

@echo off
for %%a in (001,001,500) do (
echo %%a
for %%s in (control scenario) do (
echo %%s
svic_ensemble.exe 28009_Trent_at_Colwick.cal Trent_%%s_%%a.txt 28009_Trent_at_Colwick.txt     Trent_%%s_%%a.out
)
)
pause

Many thanks

Ed

like image 418
dreab Avatar asked Dec 03 '22 03:12

dreab


2 Answers

You can solve it with string manipulations.
First prefix the number with two zeros and then take only the last three characters.

setlocal EnableDelayedExpansion
for /L %%n in (1 1 500) do (
  set "num=00%%n"
  set "num=!num:~-3!"
  echo !num!
)
like image 193
jeb Avatar answered Feb 23 '23 17:02

jeb


The easiest way of getting zero-padding is to pad with plenty of zeroes and then use a substring:

set Number=1
set PaddedNumber=000000%Number%
set PaddedNumber=%PaddedNumber:~-3%

You can adapt this for use in the loop, although you'll need delayed expansion:

setlocal enabledelayedexpansion
for /l %%a in (1, 1, 500) do (
  set num=000%%a
  set num=!num:~-3!
  for %%s in (control scenario) do (
    svic_ensemble.exe 28009_Trent_at_Colwick.cal Trent_%%s_!num!.txt 28009_Trent_at_Colwick.txt     Trent_%%s_!num!.out
  )
)
like image 31
Joey Avatar answered Feb 23 '23 17:02

Joey