Search code examples
batch-filecmdcopyfilenamesmove

windows - scan filenames and move files to dirs and subdirs with names derived from filenames


I (unfortunately) have thousands of files which need to be reorganized into different folder scheme. All my files follow the pattern:

d:\mainfolder\0001.pic\AMY_CAT_file1.jpg
d:\mainfolder\0001.pic\EVE_CAT_file1.jpg
d:\mainfolder\0002.pic\AMY_BIRD_file2.jpg
d:\mainfolder\0002.pic\EVE_BIRD_file2.jpg

what I'm looking for is a *.bat file that could move the files into folders that go like this:

...\CAT_\AMY\0001.pic\AMY_CAT_file1.jpg
...\CAT_\EVE\0001.pic\EVE_CAT_file1.jpg
...\BIRD\AMY\0002.pic\AMY_BIRD_file2.jpg
...\BIRD\EVE\0002.pic\EVE_BIRD_file2.jpg

in other words, the files would have to be moved:

  1. into the subsubfolder named after source directory of a file
  2. which is inside the folder named after 1st to 3rd symbol, and finally
  3. which is inside the folder which is named after the 5th to 8th symbol in the filename

I realise it might sound confusing, any help is greatly appreciated.


Solution

  • 1st to 3rd symbol and 5th to 8th symbol is a bad idea, as the names might be of different lengths (see cat, bird, and possibly elephant; or Eve, Amy, and possibly Stephan), but you have there a nice underscore that can serve as delimiter:

    @echo off
    setlocal EnableDelayedExpansion
    cd /d "d:\mainfolder"
    for /f "delims=" %%F in ('dir /s /b *.jpg') do (
      for /f "tokens=1,2,* delims=_" %%A in ("%%~nF") do (
        set folder=%%~dpF
        for %%X in (!folder:~0^,-1!) do (
          ECHO move "%%F" "...\%%B\%%A\%%~nxX\%%~nxF"
        )
      )
    )