DOS Batch file - Copy file based on filename elements

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

Post Reply
Message
Author
eyewon
Posts: 1
Joined: 23 Nov 2012 13:37

DOS Batch file - Copy file based on filename elements

#1 Post by eyewon » 23 Nov 2012 13:44

I need to sort alot of files based on their filename. I would like to use a batch file to do it. I do know what I want but I am not sure of the correct syntax.

Example of filenames I work with: (They are all in the same directory originally)
2012_W34_Sales_Store001.pdf
2012_W34_Sales_Store002.pdf
2012_W34_Sales_Store003.pdf

2012_November_Sales_Store001.pdf
2012_November_Sales_Store002.pdf
2012_November_Sales_Store003.pdf

I would like to extract the information that are located between the "_" signs and put them into a different variable each time. The lenght of the informations contained between the _ signs will be different everytime.

Example:
var1="2012"
var2="W34" (or November)
var3="Sales"
var4="001"
If I am able to do this, I could then copy the files to the appropriate directory using

move %var1%_%var2%_%var3%_%var4%.pdf z:\%var3%\%var4%\%var1%\%var2%
It would need to loop because I have Store001 to Store050. Also, there are not only Sales report, many others are available.

I hope I am clear.

Please help me realize this batchfile!

Squashman
Expert
Posts: 4488
Joined: 23 Dec 2011 13:59

Re: DOS Batch file - Copy file based on filename elements

#2 Post by Squashman » 23 Nov 2012 15:41

Code: Select all

@echo off
setlocal enabledelayedexpansion

for /F "tokens=1-5 delims=_." %%G in ('dir /a-d /b *.pdf') do (
   set var1=%%~G
   set var2=%%~H
   set var3=%%~I
   set var4=%%~J
   set ext=%%~K
   IF NOT EXIST z:\!var3!\!var4!\!var1!\!var2! mkdir z:\!var3!\!var4!\!var1!\!var2!
   move "!var1!_!var2!_!var3!_!var4!.!ext!" z:\!var3!\!var4!\!var1!\!var2!
)
endlocal

Post Reply