Search code examples
loopsfor-loopbatch-filemove

Batch script to iterate through directories starting with a specific string


I'm currently having to manually edit the batch file to manually tell it which directory to work on.

The directories it has to crawl will ALWAYS start with "2020-" (at least for this year), and sometimes there will be multiple of them if I miss a day.

(if it's any easier, they will ALWAYS be in this format: "0000-00-00")

Is there a way to edit this to account for that?

I've tried just making the source_directory just "2020*" but I know that's probably not how this works lol, any help or pointer in the right direction would be amazing.

@echo off

pushd %~dp0

SET source_directory=2020-05-03
SET target_directory=%~dp0

for /f %%a IN ('dir "%source_directory%" /b') do (
move %source_directory%\%%a %target_directory%
)

Solution

  • Sorry, I don't use SO too often so I forget how things need to be done.

    This is the solution I've come up with. I don't think it's the intuitive way of doing this, but I don't understand batch well enough to do this without nesting loops.

    @echo off
    
    pushd %~dp0
    
    SET source_directory=????-??-??
    SET target_directory=%~dp0
    
    for /d %%s in (%source_directory%) do (
        for /f %%a IN ('dir "%%s" /b') do (
            move %%s\%%a %target_directory%
        )
    )