Search code examples
windowsfilesyntaxcmdbatch-rename

BAT file - replace multiple characters in filename


Couldn't find an answer that wasn't very specific to someone else's problem.

I'd like to place a bat file in a directory and run it to achieve the following:

  1. Replace all initial '-' (hyphen) with ' - ' (space-hyphen-space)
  2. Replace any 3 char Month names (Jan,Feb,...Dec) with two-digit month number preceeded and followed by a hyphen ('Jan' = '-01-' , 'Mar' = '-03-')

So the following:

32432492-2015Jan23-2015Feb23.pdf 
32432492-2015Feb24-2015Mar24.pdf 
32432492-2015Mar25-2015Apr29.pdf 

becomes:

32432492 - 2015-01-23 - 2015-02-23.pdf 
32432492 - 2015-02-24 - 2015-03-24.pdf 
32432492 - 2015-03-25 - 2015-04-29.pdf 

I'd like the "rename" to only run once (instead of renaming all files over and over). It should do this for all files in current directory (except the current bat file of course).


Solution

  • @ECHO OFF
    SETLOCAL ENABLEDELAYEDEXPANSION
    SET "sourcedir=U:\sourcedir\t w o"
    FOR /f "delims=" %%a IN (
      'dir /b /a-d "%sourcedir%\*-*" '
     ) DO (
     SET "newname=%%a"
     FOR %%b IN ("Jan=-01-" "Feb=-02-" "Mar=-03-" ) DO SET "newname=!newname:%%~b!"
     FOR /f "tokens=1*delims=-" %%b IN ("!newname!") DO SET "newname=%%b - %%c"
     IF /i NOT "!newname!"=="%%a" ECHO(REN "%sourcedir%\%%a" "!newname!"
    )
    
    GOTO :EOF
    

    You would need to change the setting of sourcedir to suit your circumstances.

    I expect that you would have the sense to complete the month/number set in the form given.

    The required REN commands are merely ECHOed for testing purposes. After you've verified that the commands are correct, change ECHO(REN to REN to actually rename the files.


    Revision

    @ECHO OFF
    SETLOCAL ENABLEDELAYEDEXPANSION
    SET "sourcedir=U:\sourcedir\t w o"
    FOR /f "delims=" %%a IN (
      'dir /b /a-d "%sourcedir%\*-*" '
     ) DO (
     SET "newname=%%a"
     FOR %%b IN ("Jan=/01/" "Feb=/02/" "Mar=/03/" ) DO SET "newname=!newname:%%~b!"
     FOR /f "tokens=1,2*delims=-" %%b IN ("!newname!") DO SET "newname=%%b - %%c - %%c"
     IF /i NOT "!newname!"=="%%a" ECHO REN "%sourcedir%\%%a" "!newname:/=-!"
    )
    
    GOTO :EOF
    

    You said "Replace all initial '-' (hyphen) with ' - ' (space-hyphen-space)" which I took to mean "the initial hyphen in the name".