Jozef
Jozef

Reputation: 81

How to loop batch file path to .txt command?

I am creating file path .txt files with files names that corresspond to the day of the year. Rather than having to create a .bat file with 365 lines for each day of the year is there a simpler way to loop through in daily increments?

Currently my .bat looks like this:

dir A2018001* /a /b /s > 2018001.txt
dir A2018002* /a /b /s > 2018002.txt
dir A2018003* /a /b /s > 2018003.txt
dir A2018004* /a /b /s > 2018004.txt
dir A2018005* /a /b /s > 2018005.txt
dir A2018006* /a /b /s > 2018006.txt
dir A2018007* /a /b /s > 2018007.txt
dir A2018008* /a /b /s > 2018008.txt
dir A2018009* /a /b /s > 2018009.txt

etc....

Which works fine but is there a way to avoid having 365 lines of code in the .bat with a loop?

Im very new to using /l but I tried this:

for /l %%x in (001, 1, 365) do (
    echo %x
    dir A2018001* /a /b /s > 2018001.txt
)

and it did not cycle through the files.

Is there a way to achieve the above code with a for loop going up in increments of 1 for each day so I dont have to write it out 365 times?

Upvotes: 1

Views: 113

Answers (1)

montonero
montonero

Reputation: 1721

You've done the code almost correctly. Just need to pad the variable with zeroes.

setlocal enabledelayedexpansion
for /l %%x in (1,1,365) do (
    set "d=00%%x"
    set "d=!d:~-3!"
    dir "A2018!d!*" /a /b /s > "2018!d!.txt"
)

Upvotes: 1

Related Questions