Solved

How do I create a script that can move files to an existing directory based on filename?

Posted on 2010-08-20
21
484 Views
Last Modified: 2012-05-10
Hello

Let me preface this by saying that I know nothing about computer programming.

I need a script that can pickup files from a dump folder (i.e, J:\ScanFiles\Fax dump) and move them to different folders (which already exist), based on the ID portion of the filename.

For example, a file in J:\ScanFiles\Fax dump would be named "1056_7_22_10.pdf"  "1056" is the ID; note that this number could potentially be 6 figures or perhaps greater.  So there could also be a "1056_7_23_10.pdf" etc. in Fax dump.  These files should be moved to J:\ScanFiles\1056  This directory doesn't need to be created as it already exists.

So, as another example, a file in J:\ScanFiles\Fax dump named "51608_7_23_10.pdf" should be moved to J:\ScanFiles\51608   Again the destination directory already exists, the file just needs to be moved.

Thanks so much for your help!

Mike
0
Comment
Question by:jumptohigh
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 7
  • 5
  • 3
  • +3
21 Comments
 
LVL 14

Expert Comment

by:peetjh
ID: 33487833
Try creating a batch file with this code. You can of course remove the pause.

@echo off
j:
cd \
cd scanfiles
cd fax dump
move 1056* j:\scanfiles\fax dump\1056\
move 51608* j:\scanfiles\fax dump\51608\
pause
exit
0
 
LVL 14

Expert Comment

by:peetjh
ID: 33487838
sorry on the move lines remove the fax dump\ so it goes to the right path
0
 
LVL 10

Expert Comment

by:answer_dude
ID: 33487894
Put the code below into a .VBS file and run the file
Option Explicit

Sub MyCopyFile(sFile, sSourceDir, sTargetDir)
'Copies file, sFile from sSourceDir to sTargetDir
'sFile can be wildcards, e.g., "*.*" or "app??.txt" etc.
'sSourceDir and sTargetDir should both contain the final "backslash" in the path

    Dim fso

    'MyCopyFile = False

    If (Right(sSourceDir, 1) <> "\") Then
        sSourceDir = sSourceDir & "\"
    End If

    If (Right(sTargetDir, 1) <> "\") Then
        sTargetDir = sTargetDir & "\"
    End If

    On Error Resume Next
    Set fso = CreateObject("Scripting.FileSystemObject")
    fso.CopyFile sSourceDir & sFile, sTargetDir
    Set fso = Nothing

    'If (fso.FileExists(sTargetDir & sFile)) Then
    '    MyCopyFile = True
    'End If

End Sub

Sub LoopThroughFilesInFolder()

Dim FSO, FLD, FIL
Dim strFolder
Dim sTarget
Dim n

	'Change as needed
	strFolder = "J:\ScanFiles\Fax dump"
    If Right(strFolder, 1) <> "\" Then strFolder = strFolder & "\"
	'Create the filesystem object
	Set FSO = CreateObject("Scripting.FileSystemObject")
	'Get a reference to the folder you want to search
	set FLD = FSO.GetFolder(strFolder)
	
	'loop through the folder and get the file names
	For Each Fil In FLD.Files
		'MsgBox Fil.Name
        n = Instr(1, Fil.Name, "_")
        If n > 0 Then
            sTarget = Left(Fil.Name,n-1)
            'msgbox strFolder & Fil.Name & vbcrlf & strFolder & sTarget
            Call MyCopyFile(Fil.Name, strFolder, strFolder & sTarget)
        End If
	Next
	
    'Clean up
    Set FLD = Nothing
    Set FSO = Nothing
    
End Sub

Call LoopThroughFilesInFolder

Open in new window

0
DevOps Toolchain Recommendations

Read this Gartner Research Note and discover how your IT organization can automate and optimize DevOps processes using a toolchain architecture.

 
LVL 10

Expert Comment

by:answer_dude
ID: 33487948
Actually, the code above just copies the files into the new folders... I tweaked it to MOVE the files.
Option Explicit

Sub MyMoveFile(sFile, sSourceDir, sTargetDir)
'Copies file, sFile from sSourceDir to sTargetDir
'sFile can be wildcards, e.g., "*.*" or "app??.txt" etc.
'sSourceDir and sTargetDir should both contain the final "backslash" in the path

    Dim fso

    If (Right(sSourceDir, 1) <> "\") Then
        sSourceDir = sSourceDir & "\"
    End If

    If (Right(sTargetDir, 1) <> "\") Then
        sTargetDir = sTargetDir & "\"
    End If

    On Error Resume Next
    Set fso = CreateObject("Scripting.FileSystemObject")
    fso.MoveFile sSourceDir & sFile, sTargetDir
    Set fso = Nothing

End Sub


Sub LoopThroughFilesInFolder()

Dim FSO, FLD, FIL
Dim strFolder
Dim sTarget
Dim n

	'Change as needed
	strFolder = "J:\ScanFiles\Fax dump"

    If Right(strFolder, 1) <> "\" Then strFolder = strFolder & "\"
	'Create the filesystem object
	Set FSO = CreateObject("Scripting.FileSystemObject")
	'Get a reference to the folder you want to search
	set FLD = FSO.GetFolder(strFolder)
	
	'loop through the folder and get the file names
	For Each Fil In FLD.Files
		'MsgBox Fil.Name
        n = Instr(1, Fil.Name, "_")
        If n > 0 Then
            sTarget = Left(Fil.Name,n-1)
            'msgbox strFolder & Fil.Name & vbcrlf & strFolder & sTarget
            Call MyMoveFile(Fil.Name, strFolder, strFolder & sTarget)
        End If
	Next
	
    'Clean up
    Set FLD = Nothing
    Set FSO = Nothing
    
End Sub

Call LoopThroughFilesInFolder

Open in new window

0
 
LVL 10

Expert Comment

by:Casey Herman
ID: 33488132
Meh... you would need to set up a scheduled task to periodically check your directory and do the moves...  but this would work:

Two batch files. The first one is the scheduled job called read.bat that just looks in the directory and processes all files that match the file spec. In my example, it is .txt. For each file, it calls the parse.bat, which extracts the data from the filename. You could do much more with this than just move the file... but the end result is that it is moved to the directory that matches the prefix.


read-bat.txt
0
 
LVL 10

Expert Comment

by:Casey Herman
ID: 33488141
Eep...didnt let me upload the parser

It is a lot simpler than a lot of vb code and accomplishes the task

Hope this helps
parse-bat.txt
0
 
LVL 10

Expert Comment

by:Casey Herman
ID: 33488188
This can be done easily with a one line command using robocopy and appropriate switches.
0
 
LVL 13
ID: 33488250
Sadly my phone difn't post this the first time, and then was dropped, so has to be retyped:


Copy everything below the following line into notepad, and save it as "MovePDF.bat
"

::---------------------------------------------------------
ECHO OFF
FOR /F "Tokens=1,2* Delims=_" %%F IN ('DIR /A:-D "J:\ScanFiles\Fax dump\*.pdf" /B ') DO MOVE
"J:\ScanFiles\Fax dump\%%F_%%G" "J:\ScanFiles\%%F\%%F_%%G" /Y
0
 
LVL 55

Accepted Solution

by:
Bill Prew earned 250 total points
ID: 33488838
This should get the job done.  Save as a BAT file, and if needed adjust the first two SET statements to reference your paths.  Then just run the BAT file at a command prompt.  Do not add any double quotes around these paths even if they contain spaces.

I assumed you were only processing PDF files, but if needed we can adjust that easy.

~bp
@echo off
set BaseDir=j:\scanfiles\fax dump
set DestDir=j:\scanfiles
for %%A in ("%BaseDir%\*_*.pdf") do (
  for /F "tokens=1 delims=_" %%B in ("%%~nA") do (
    move "%%A" "%DestDir%\%%B\"
  )
)

Open in new window

0
 

Author Comment

by:jumptohigh
ID: 33488868
Qcubed,

Thanks so much for your help!

I ran MovePDF.bat and received the following errors:

J:\>MovePDF.bat
J:\>ECHO OFF
The syntax of the command is incorrect.
The syntax of the command is incorrect.
The syntax of the command is incorrect.
The syntax of the command is incorrect.
'"J:\ScanFiles\Fax dump\%F_%G"' is not recognized as an internal or external command,
operable program or batch file.

Perhaps I'm doing something wrong here...

Mike
0
 
LVL 13
ID: 33488896
here is my code redone in the code window instead of by BB, looks like even though when I started writing the code there were 0 responders a lot of people were able to type up responses far quickly from their computers..

The following script will handle your request, same as I had posted 1.5 times above.

I added a quick check that the directory you are moving to exists JUST in case

ECHO OFF
FOR /F "Tokens=1,* Delims=_" %%F IN ('DIR /A:-D "J:\ScanFiles\Fax dump\*_*.pdf" /B ') DO MOVE "J:\ScanFiles\Fax dump\%%F_%%G" "J:\ScanFiles\%%F\%%F_%%G" /Y

Open in new window

0
 
LVL 13
ID: 33488940
Sorry the reason you are getting that is I put the /Y AFTER the directories (I am too used to Robocopy), here it is corrected and I tested it to verify it works silly typo error.

ECHO OFF
FOR /F "Tokens=1,* Delims=_" %%F IN ('DIR /A:-D "C:\Users\EnochRoot\*_*.pdf" /B ') DO MOVE /Y "C:\Users\EnochRoot\%%F_%%G" "C:\Users\%%F\%%F_%%G"

Open in new window

0
 
LVL 13
ID: 33488979
-______-  Okay well i just pasted you the one with MY directory for testing instead of yours.  the attached code is YOUR directory.  Please node the attached code does as you requested and copies if the folder exists otherwise you get an error saying the folder does not exist..  two things we could easily do:

1. create the folder if it doesn't' exist
2. check if the folder exists before copy attempt, and not copy if the folder does not exist.

do either of these interest you? I already have both versions created.

ECHO OFF
FOR /F "Tokens=1,* Delims=_" %%F IN ('DIR /A:-D "J:\ScanFiles\Fax dump\*_*.pdf" /B ') DO MOVE /Y "J:\ScanFiles\Fax dump\%%F_%%G" "J:\ScanFiles\%%F\%%F_%%G"

Open in new window

0
 

Author Closing Comment

by:jumptohigh
ID: 33488991
Great job billprew!  Works beautifully.

One quick question, if I add an additional suffix "_s" to the filename (i.e., 4367_07_22_10_s.pdf)  will the script still work fine?

Mike
0
 
LVL 55

Expert Comment

by:Bill Prew
ID: 33489007
Yes, the script will still work fine.  It looks for files matching *_*.pdf so as long as there is at least one underscore it will process the file.

Glad that worked out, thanks.

~bp
0
 
LVL 13
ID: 33489008
NOTE About Running this:

  You can run this command by double clicking the batch file, or make a scheduled task to run it.

Or you can type it at the command prompt but if you type it at the command prompt each %%F and %%G must be typed %F and %G instead.
0
 
LVL 13
ID: 33489021
lol Damn my BlackBerry 8830!!  
0
 

Author Comment

by:jumptohigh
ID: 33489088
Qcode,

That worked perfectly!

Can we also do #2 check if the folder exists before copy attempt, and not copy if the folder does not exist?

Can we get an alert that says the folder doesn't exist?

Also, I am new to experts-exchange... how do I give you credit as well if I already clicked solution worked?

Thanks so much,
Mike
0
 

Author Comment

by:jumptohigh
ID: 33489092
whoops, I meant QCubed
0
 
LVL 13
ID: 33489139
yes, we can alert in a dos window that the folder doesn't exist, or install blat and send an email if you like.  but either one will require a few more lines, which woudl you prefer.

In the mean-time we can create the folder in a single line.  attached is the code to automatically create the folder if it doesn't exist.

To re-split points you have to scroll to your initial posting and click the little button that says "Request Attention" then type in to the request to have the question re-opened to give out hte points.

~Q

ECHO OFF
FOR /F "Tokens=1,* Delims=_" %%F IN ('DIR /A:-D "J:\ScanFiles\Fax dump\*_*.pdf" /B ') DO MD "J:\ScanFiles\%%F\"&MOVE /Y "J:\ScanFiles\Fax dump\%%F_%%G" "J:\ScanFiles\%%F\%%F_%%G"

Open in new window

0
 

Author Comment

by:jumptohigh
ID: 33489357
QCubed,

Thanks again....

I only need a DOS window indicating that the folder doesn't exist.  I don't need it to automatically create the folder as this has already been created by another program.

Mike
0

Featured Post

DevOps Toolchain Recommendations

Read this Gartner Research Note and discover how your IT organization can automate and optimize DevOps processes using a toolchain architecture.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Introduction: Recently, I got a requirement to zip all files individually with batch file script in Windows OS. I don't know much about scripting, but I searched Google and found a lot of examples and websites to complete my task. Finally, I was ab…
With User Account Control (UAC) enabled in Windows 7, one needs to open an elevated Command Prompt in order to run scripts under administrative privileges. Although the elevated Command Prompt accomplishes the task, the question How to run as script…
In this brief tutorial Pawel from AdRem Software explains how you can quickly find out which services are running on your network, or what are the IP addresses of servers responsible for each service. Software used is freeware NetCrunch Tools (https…
Monitoring a network: why having a policy is the best policy? Michael Kulchisky, MCSE, MCSA, MCP, VTSP, VSP, CCSP outlines the enormous benefits of having a policy-based approach when monitoring medium and large networks. Software utilized in this v…

726 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question