Improve company productivity with a Business Account.Sign Up

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 493
  • Last Modified:

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

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
jumptohigh
Asked:
jumptohigh
  • 7
  • 5
  • 3
  • +3
1 Solution
 
JPIT DirectorCommented:
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
 
JPIT DirectorCommented:
sorry on the move lines remove the fax dump\ so it goes to the right path
0
 
answer_dudeCommented:
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
Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

 
answer_dudeCommented:
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
 
Casey HermanCitrix EngineerCommented:
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
 
Casey HermanCitrix EngineerCommented:
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
 
Casey HermanCitrix EngineerCommented:
This can be done easily with a one line command using robocopy and appropriate switches.
0
 
Ben Personick (Previously QCubed)Lead Network EngineerCommented:
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
 
Bill PrewCommented:
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
 
jumptohighAuthor Commented:
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
 
Ben Personick (Previously QCubed)Lead Network EngineerCommented:
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
 
Ben Personick (Previously QCubed)Lead Network EngineerCommented:
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
 
Ben Personick (Previously QCubed)Lead Network EngineerCommented:
-______-  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
 
jumptohighAuthor Commented:
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
 
Bill PrewCommented:
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
 
Ben Personick (Previously QCubed)Lead Network EngineerCommented:
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
 
Ben Personick (Previously QCubed)Lead Network EngineerCommented:
lol Damn my BlackBerry 8830!!  
0
 
jumptohighAuthor Commented:
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
 
jumptohighAuthor Commented:
whoops, I meant QCubed
0
 
Ben Personick (Previously QCubed)Lead Network EngineerCommented:
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
 
jumptohighAuthor Commented:
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
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Keep up with what's happening at Experts Exchange!

Sign up to receive Decoded, a new monthly digest with product updates, feature release info, continuing education opportunities, and more.

  • 7
  • 5
  • 3
  • +3
Tackle projects and never again get stuck behind a technical roadblock.
Join Now