0

I have lots of image files named as YYYYMMDD_HHmm.jpg

How can I move these files to: target_directory\YYYY\MM\YYYYMMDD_HHmm.jpg ?

Thank you

2 Answers2

3

You can use a for loop, substrings, and mkdir:

@echo off
setlocal enabledelayedexpansion

for /f %%a in ('dir /b /a-d') do (
    set filename=%%a

    ::exclude this file
    if not "!filename!" == "%~nx0" (

        ::substr to grab characters 0-4 and 4-6 as year and month
        set year=!filename:~0,4!
        set month=!filename:~4,2!

        ::make dirs for the files if they don't already exist
        if not exist !year! mkdir !year!
        if not exist !year!\!month! mkdir !year!\!month!

        ::move the files there
        move !filename! !year!\!month!
    )
)

The for loop runs dir /b /a-d which returns all files in the current directory except folders. Substring notation is !variable:~start,length!.

What is the best way to do a substring in a batch file?

Community
  • 1
  • 1
Joel I
  • 146
  • 2
0

One-liner for the command prompt:

for %a in (*.jpg) do @set "FName=%~a"&call xcopy "%FName%" "%FName:~0,4%\%FName:~4,2%\"&&del "%~a"&set "FName="
Endoro
  • 37,015
  • 8
  • 50
  • 63