Batch file to sort files by name

So we have electronic journals that get dumped into a folder. These are things we need to keep. However having them all thrown into the same folder can also be a pain.  Not only does it just cause a bunch of files to be in one folder but I we need to look back at Jan 18th 2017 we’d have to sort through tons and tons of these files looking for the one we wanted.

So I wrote this bat file that basically looks at out file name and puts everything into it’s own separate folder.

So first I’ll post the code then I’ll explain.

@echo off

setlocal enabledelayedexpansion


pushd c:\sortfolder\

for /f "tokens=*" %%1 in ('dir /a-d /b c:\EJ\*.JRN') do (

set filename=%%1&set dirname=!filename:~0,2!\!filename:~2,2!\!filename:~4,2!

if not exist c:\sortedfolder\20!dirname!\ (md c:\sortedfolder\20!dirname!\)

move %%1 c:\sortedfolder\20!dirname!\>nul


Now out file format looks like this 18091700-000101Z.JRN

Now the only part we’re really interested in is

(180917) 00-000101Z.JRN

18 year, 09 month, 17 day.

Now this does all the sorting.

set filename=%%1&set dirname=!filename:~0,2!\!filename:~2,2!\!filename:~4,2!

!filename:~0,2! – Starts at the first character and goes two over so it grabs 18

!filename:~2,2! – Starts after the second character and goes 2 over so 09

!filename:~4,2! – Starts after the 4th character

If you adjust the first and last number you can sort by other setups.

So !filename:~0,4! Would start and go to include 1809

Leave a Reply

Your email address will not be published. Required fields are marked *