Search code examples
batch-filecmd

Batch: If filename on source folder contains x, move to x destination folder


I have a batch script that moves all the files on a folder to another, but I want to insert a variable here, like: If any file on that folder contains the name or part of the name, for example, "house", move that file to "houses" folder, and if contains "dog", move to "dog" folder. Remember, is part of the name, not the extension of the file.

Part of my script that works is this, but this move all files:

@echo off

move D:\"FUNDACIÓN CB"\"Carteles temp"\*.* D:\"FUNDACIÓN CB"\"Carteles antiguos"

Solution

  • @ECHO Off
    SETLOCAL ENABLEDELAYEDEXPANSION
    rem The following settings for the source directory, destination directory, target directory,
    rem batch directory, filenames, output filename and temporary filename [if shown] are names
    rem that I use for testing and deliberately include names which include spaces to make sure
    rem that the process works using such names. These will need to be changed to suit your situation.
    SET "sourcedir=u:\your files"
    SET "destdir=u:\your results"
    
    FOR /f "delims=" %%s IN (
     'dir /b /ad "%destdir%\*" '
     ) DO (
     FOR /f "delims=" %%a IN (
      'dir /b /a-d "%sourcedir%\*%%s*" 2^>nul'
      ) DO (
      SET "match=%%~na"
      IF "%%~na" neq "!match:%%s=!" MOVE "%sourcedir%\%%a" "%destdir%\%%s\" >nul
     )
    )
    MOVE "%sourcedir%\*" "%destdir%\"
    

    First, collect the directorynames present in the destination directory and assign each to %%s in turn.

    With each, look for filenames which contain the directoryname %%s and then check that the name part of the file contains the directoryname by using delayedexpansion and removing the directoryname from the filename. If the filename indeed includes the directoryname, then move the file %%a from the source directory to the subdirectory found.

    Finally. when each subdirectoryname has been processed, move the remaining files from source to destination directory.