Search code examples
windowswindows-7file-renamebatch-rename

Renaming Multiple Files


I have almost 2000 files which I need to rename.

The files are named in the following format: PART1#PART2#PART3.pdf

I would like to batch rename the files so that PART2 is moved before PART1 e.g. PART2#PART1#PART3.pdf

PART 1 = A random document reference e.g. 124244
PART 2 = A reference number e.g. 12-12434-A
PART 3 = A short description e.g. Part 1

The # symbol separates each of these parts.

Is there a simple utility which I can use to make this change?


Solution

  • Use a batch file

    @echo off
        setlocal enableextensions disabledelayedexpansion
    
        cd /d "c:\where\thefiles\are"
    
        for /f "tokens=1,2,* delims=#" %%a in ('
            dir /b /a-d *.pdf ^| findstr /r /b /e /i /c:"[^#][^#-]*#[^#][^#]*#..*\.pdf"
        ') do echo ren "%%a#%%b#%%c" "%%b#%%a#%%c"
    

    What this code does is

    1. Get the file list: a dir command asking for .pdf files in a bare format without the folders

    2. Filters to only get the adecuated files: findstr command, searching for a regular expression that matches the beginning and end of the lines, ignoring case. The expression that is tested against the file names is : a non # character, followed by a sequence of non # or - characters (to avoid renaming the files twice), followed by a #, followed by a non # and a sequence of non # characters, followed by a # and any sequence of characters ending in .pdf

    3. The for command splits the names using the # as token delimiter and for each one do the rename.

    Rename operations are only echoed to console. If the output is correct, remove the echo command