Search code examples
batch-filecmdwindows-vistafile-renamebatch-rename

How to remove a prefix from multiple files?


I downloaded a lot of videos that are named like [site.com] filename.mp4 and I wanted to remove the prefix so that they are named like filename.mp4.

I tried a batch file with the following code:

ren "[site.com] *.mp4" "///////////*.mp4"

But the result was .com] filename.mp4 and can't rename anything beyond the dot, any ideas?


Solution

  • @ECHO OFF
    SETLOCAL
    SET "sourcedir=U:\sourcedir"
    FOR /f "tokens=1*delims=]" %%a IN (
     'dir /b /a-d "%sourcedir%\*" '
     ) DO IF "%%b" neq "" (
     FOR /f "tokens=*" %%h IN ("%%b") DO ECHO(REN "%sourcedir%\%%a]%%b" "%%h"
    )
    
    GOTO :EOF
    

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

    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.

    Perform a directory scan of the source directory, in /b basic mode /a-d without directories and tokenise each filename found - the part before the first ] to %%a and the remainder to %%b.

    If %%b is not empty (ie. did not contain ]) then do nothing, therwise use the default token set (which includes space) and tokens=0 to strip the leading spaces from %%b into %%h, then build the original filename and rename.