Super User is a question and answer site for computer enthusiasts and power users. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I have a script which does not work:

set /a num=0
for /L %%C in (1,1,31) do (
        set /a num+=1
        set day=%num%
        for /r %%1 in ("Folder\Day_%num%.txt") do echo %num%

I need the number from 1 to 31 generated in a loop to be a string variable which could be used to create a file name. In my case there is a problem to use both the parameter %%C or numeric variable "num" for this purpose. I tried to set a string variable "day" which keeps the number of interest but it still does not work I do not know why. Please help to fix it.

share|improve this question

not sure if I understood well what you really want to do, but here is code that is going to create for you empty files containing requested number in name. If it is not the answer you are looking for, please be more specific with your request.

FOR /L %%C IN (1,1,31) DO (
    ECHO. >> "Folder\Day_%%C.txt"

NOTE: Please make sure that "Folder" directory exists.

share|improve this answer
Thanks this code works fine but only when date is in the range 1-9. In this case I entre "Folder\Day_0%%C.txt". But it is does not work for further two digit numbers starting from 10. I still do not have solution to do that for all 31 days when %%C changes from being of one digit to two digits – Anna May 14 '12 at 1:55

I think you've made the script overly complicated. Try this:

for /L %%C in (1,1,31) do (
  for /r %1 %%D in ("Folder\Day_%%C.txt") do echo %%D

A couple of notes:

Batch treats all variables as strings except when using set /a.

The for /L will do the counting for you, no need to do extra addition.

It's easy to confuse the double percent syntax (%%C) required for the for loop with the single percent syntax (%1) used to access arguments passed to the script from the command line. Just be aware that command line args only use the single percent syntax.

I'm not sure what you second for loop is supposed to be doing. You needed another loop variable there (%%D) for it to work. I suspect you're trying to output the lines of the file Day_1.txt, Day_2.txt, etc., but I don't think it's going to work the way it's currently written, especially if you need to create the file first.

Edit in response to comment attached to evianton's answer:

You didn't specify that you needed 2-digit days in your original question. The code below (modified from evianton) should solve that issue.

@echo off
setlocal enabledelayedexpansion
for /l %%C in (1,1,31) do (  
  set num=%%C  
  if %%C lss 10 set num=0%%C  
  echo. >> "Folder\Day_!num!.txt"  
share|improve this answer

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .