Search code examples
batch-filecreate-directorymovefile

Batch File to organise pictures from mobile phone into folders (on Windows)


I just created my first Batch file, to organise my mobile phone pictures into folders (on Windows). It worked, I am just wondering if there is a more efficient way in coding this, as in its current form I would have to go through all possible combinations of years and months.

if exist 2018*.* md 2018
if exist 2019*.* md 2019
if exist 2020*.* md 2020
move    2018*.* 2018
move    2019*.* 2019
move    2020*.* 2020
if exist 2018\????_03_*.* md 2018\March
if exist 2018\????_04_*.* md 2018\April
if exist 2018\????_05_*.* md 2018\May
move    2018\????_04_*.*    2018\April
move    2018\????_05_*.*    2018\May
move    2018\????_03_*.*    2018\March
if exist 2019\????_03_*.* md 2019\March
if exist 2019\????_04_*.* md 2019\April
if exist 2019\????_05_*.* md 2019\May
move    2019\????_04_*.*    2019\April
move    2019\????_05_*.*    2019\May
move    2019\????_03_*.*    2019\March
if exist 2020\????_03_*.* md 2020\March
if exist 2020\????_04_*.* md 2020\April
if exist 2020\????_05_*.* md 2020\May
move    2020\????_04_*.*    2020\April
move    2020\????_05_*.*    2020\May
move    2020\????_03_*.*    2020\March

Solution

  • @echo off
    
    for /f "tokens=1,2,* delims=_" %%A in ('
        dir /b /a-d ????_??_*.* ^| findstr /b "20[0-9][0-9]_"
    ') do (
        for %%D in (
            "01 January"
            "02 February"
            "03 March"
            "04 April"
            "05 May"
            "06 June"
            "07 July"
            "08 August"
            "09 September"
            "10 October"
            "11 November"
            "12 December"
        ) do (
            for /f "tokens=1,2" %%E in ("%%~D") do (
                if "%%~B" == "%%~E" (
                    if not exist "%%~A\%%~F\" md "%%~A\%%~F\"
                    if exist "%%~A\%%~F\" move "%%~A_%%~B_%%~C" "%%~A\%%~F\" >nul
                )
            )
        )
    )
    

    This uses the ????_??_*.* pattern and is allowed if findstr detects the 1st four characters as digits of a year in the 21st century with a following underscore. It then gets the month from the 2 digits in the 2nd token. It checks if directory year\month\ exists and creates it if not exist. If directory year\month\ exist, copies the file into the directory.

    for variables:

    • A year digits
    • B month digits
    • C remainder of filename
    • D month digits and name
    • E month digits
    • F month name

    View for /? for help with understanding a for loop.