'Batch - Move file that start with pattern to a certain folder

I have a list of files organized like this: test%MM%YYYY%DD.txt, for example:

test01201401.txt
test01201402.txt
test01201403.txt
...
test02201401.txt
test02201402.txt
...

I would like to create monthly-based folders like \test%MM%YYYY (e.g. \test012014 or \test022014) and then move all the daily based .txt files into the respective folder, for example all test012014* files are moved to the \test012014 folder and all test022014* files are moved to the \test022014 folder and so on. Thanks!



Solution 1:[1]

@echo off
setlocal enabledelayedexpansion
for /f %%f in ('dir /b ^| findstr /r "^test[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]\.txt$"') do (
    set "filename=%%~nf"
    if not exist "!filename:~0,10!" md "!filename:~0,10!"
    move "%%~f" "!filename:~0,10!"
)

For every filename that matches this regex ^test[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]\.txt$ (a filename starting with test, followed by 8 digits, and ending with .txt), it checks if a folder whose name matches the first 10 characters of the filename (t e s t M M Y Y Y Y) already exists, if not it creates it, then it moves the file there.

Solution 2:[2]

example

p:\DANE\telefony\Marcin\Archiwum>..\..\move-archive.bat
move IMG-20220119-WA0000.jpg 2022\2022-01\
move IMG-20220119-WA0001.jpg 2022\2022-01\

code

@echo off
rem not %var% but !var! give us access to internal loop variable value with enabledelayedexpansion.
setlocal enabledelayedexpansion
rem Run by scheduler script in p:\dane\telefony\marcin\move-archive.bat
rem p:
rem cd p:\dane\telefony\marcin\archiwum
FOR %%V IN (*.*) DO (
rem echo "****** %%V *********"
SET filedate=%%~tV
rem echo !filedate!
SET fileyear=!filedate:~6,4!
rem echo !fileyear!
SET filemonth=!filedate:~3,2!
rem echo !filemonth!
rem create directory as yyyy\yyyy-MM
mkdir !fileyear!\!fileyear!-!filemonth! 2>nul
echo move %%V !fileyear!\!fileyear!-!filemonth!\
move %%V !fileyear!\!fileyear!-!filemonth!\ >nul
)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 SiB