Create folder from first 8 char & move files based on same criteria

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

Post Reply
Message
Author
tkeneda
Posts: 2
Joined: 05 Oct 2020 14:09

Create folder from first 8 char & move files based on same criteria

#1 Post by tkeneda » 05 Oct 2020 14:20

I am not an expert in any way but have looked at other posts and modified the following. Would love if someone could confirm. I have one directory with several thousand .jpg files. The first 8 characters of the file names are the shot date YYYYMMDD_image##.jpg - I need to create a directory for every date, and move all the files from that date into that directory, whether 1 file or a 1000 files. Thank you.

From this:

Code: Select all

D:\iphone pics dump\
	20150401_imagefile001.jpg
	20150401_imagefile002.jpg
	20150501_imagefile001.jpg
	20160115_imagefile099.jpg
	 (. . . X 26K)
To this:

Code: Select all

D:\20150401\
	20150401_imagefile001.jpg
	20150401_Imagefile002.jpg
D:\20150501\
        20150501_imagefile001.jpg
D:\20160115\
	20160115_imagefile099.jpg

Code: Select all

@echo off
setlocal enabledelayedexpansion
for %%A in (*.jpg) do (
   echo file found  %%A
   for /f "delims=" %%B in ("%%A") do set fname=%%~nB
   for /f "delims=" %%C in ("%%A") do set fextn=%%~xC
   for /f "tokens=1* delims=_" %%D in ("!fname!") do set folname=%%D
   echo folder name !folname!
   if not exist "!folname!" (
      echo Folder !folname! does not exist, creating
      md "!folname:~0,8!."
   ) else (
      echo Folder !folname! exists
   )
   echo Moving file %%A to folder !folname!
   move "%%A" "!folname!"
   )
echo Finished
pause
Last edited by aGerman on 06 Oct 2020 04:02, edited 1 time in total.
Reason: Code formatting (also for text where indentation is important)

aGerman
Expert
Posts: 4678
Joined: 22 Jan 2010 18:01
Location: Germany

Re: Create folder from first 8 char & move files based on same criteria

#2 Post by aGerman » 06 Oct 2020 09:54

Paths are taken from your example. You may have to update them.

Code: Select all

@echo off &setlocal
set "src=D:\iphone pics dump"
set "dst=D:"

cd /d "%src%"
for %%i in (*_image*.jpg) do (
  for /f "delims=_" %%j in ("%%~i") do (
    if not exist "%dst%\%%j\" md "%dst%\%%j"
    move "%%~i" "%dst%\%%j\"
  )
)
Steffen

tkeneda
Posts: 2
Joined: 05 Oct 2020 14:09

Re: Create folder from first 8 char & move files based on same criteria

#3 Post by tkeneda » 06 Oct 2020 13:27

Thank you!

Post Reply