emcaleer
emcaleer

Reputation: 11

batch auto move files based on partial filename

I'm new to batch and only have a very basic understanding of what to do.

I have hundreds of files that I would like to sort into folders based on the name. An example of the filename would be:

346479_2009-01-01_2009-12-31_Distribution_Report

For example, there is 2 Distribution Reports (one pdf, on csv) for 2009 through 2014, I want to move (or copy, it doesn't matter) all the Distribution Reports into one folder, labeled Distribution Report.

If someone could help I would really appreciate it!

I was working off this post but not having much luck... this was all I got, and I don't think it is at all correct:

    @ECHO OFF
    SETLOCAL
    SET "sourcedir=C:\Users\emcaleer\Desktop\New folder"
    PUSHD %sourcedir%
    FOR /f "tokens=1*" %%a IN (
     'dir /b /a-d "*_*_*-*-*-*_*-*-*-*_"'
     ) DO (  
     MD %%a
     MOVE "%%a %%b" .\%%a\
    )
    POPD
    GOTO :EOF

Upvotes: 1

Views: 1604

Answers (1)

Stephan
Stephan

Reputation: 56180

for Syntax can be a bit confusing for beginners. You specified Tokens, but no delimiter. Because there are None of the Default delimiters in the string, the second token never got any value. Try this:

@echo off
setlocal enabledelayedexpansion

for /f "delims=" %%i in ('dir /b /a-d *_*_*_*.*') do (
  set file=%%~ni
  set folder=!file:*-31_=!
  md !folder! 2>nul
  move "%%i" !folder!
)

Upvotes: 1

Related Questions