Search code examples
windowsbatch-filemove

Batch script to move files that match another set of files?


This would help me a lot of possible.

Example: Folder1 has 900 files ending in .zip. Folder2 has 300 files that match the ones in Folder1 but in .doc

How can I create a batch script to move files from Folder1 to Folder1-sorted that only have a .doc alternative ending up with a folder1-sorted with only 300 .zip files?

My initial guess was doing dir > list.txt and changing the extension of every line and using this list to copy.. but I guess there might be a more clever solution to doing this.


Solution

  • With the aid of Setlocal EnableDelayedExpansion and For loops you could build an indexed array whose values contain just the filenames for your .doc files, using the ~n variable modifier, then use another for loop on your .zip files to compare against the array with a nested For /L loop.

    EG:

    @ECHO OFF & Setlocal EnableDelayedExpansion
    CD "your path for parent directory containing folders 1 and 2"
    
    REM build the array using the smaller data set...
    
    PUSHD Folder2
    Set "_I=0"
    For %%A in (*.doc) Do (
        Set /A _I+=1
        Set "file[!_I!]=%%~nA"
    )
    POPD
    PUSHD Folder1
    For %%A in (*.zip) Do (
        For /L %%B in (1,1,!_I!) Do (
            If "!file[%%B]!"=="%%~nA" (
                ECHO(%%A matches !file[%%B]!.doc
    REM command for on Match here
            )
        )
    )
    POPD