CLO_471
CLO_471

Reputation: 125

Renaming batch of files using DOS batch script or vbscript

I am looking for either a batch script or vbscript, (preferably a vbscript) that will help me rename an entire folder of about 5,000 or so files.

The files to be renamed have names in this format: nnnnnnnnnnnnnnnn.dddddddd.pdf where n is a no. 0-9 and d is a date in this example format 01232009 (January 23, 2009).

I need to be able to take the last 4 d's of the file name and move them in front of the first four d's of the file name. All file names are consistent and use the same exact format. Here is an example of what I am trying to accomplish:

nnnnnnnnnnnnnnnn.01232009.pdf ==> nnnnnnnnnnnnnnn.20090123.pdf

This is so that when I sort the files they can be sorted in ascending or descending order by date. Any idea of how to make this work?

Upvotes: 1

Views: 2396

Answers (2)

PA.
PA.

Reputation: 29339

for a pure .BAT solution, try this

@echo off
SETLOCAL enabledelayedexpansion
FOR %%a IN (*.*) DO (
  CALL :cn %%a
  echo REN %%a !a!
)
GOTO :eof
:cn
SET a=%1
SET a=%a:~0,-13%.%a:~-8,4%%a:~-12,4%.pdf
GOTO :eof

after careful testing, remove the echo command

Upvotes: 1

Cheeso
Cheeso

Reputation: 192487

This is basically the same script as in the answer to your previous question.
It just does something different with the dates.
Also, it echoes the filenames so you can see what it is doing.

It will fail if the target file already exists.

Const IN_PATH = "path_to\directory"
Const OUT_PATH = "path_to\directory"

dim fso: set fso = CreateObject("Scripting.FileSystemObject")
if not fso.FolderExists(IN_PATH) then
    err.raise 1,, "Path '" & IN_PATH & "' not found"
end if
if not fso.FolderExists(OUT_PATH) then
    err.raise 1,, "Path '" & OUT_PATH & "' not found"
end if

dim infolder: set infolder = fso.GetFolder(IN_PATH)
dim file
for each file in infolder.files
    dim name: name = file.Name
    dim parts: parts = split(Name, ".")

    ' Look for a file format of nnnnnnnnnnnnnnnn.dddddddd.pdf
    ' where the first segment is (I don't care) and dddddddd is
    ' a date, encoded.  for example 01232009 implies (January
    ' 23, 2009).
    If UBound(parts) = 2 And parts(2) = "pdf" And Len(parts(1)) = 8 Then
        ' build a new name, re-arranging the date
        dim newname: newname = parts(0) & "." & _
            Mid(parts(1), 5, 4) & Mid(parts(1), 1, 4) & "." & parts(2)
        ' use the move() method to effect the rename
        WScript.Echo Name & " ==> " & newname
        file.move fso.buildpath(OUT_PATH, newname)
    Else
        WScript.Echo "Not renaming file: '" & name & "'"
    End If
Next 'file

Upvotes: 1

Related Questions