Search code examples
batch-filefile-renamebatch-rename

File renaming batch script


I'm trying to rename a bunch of files, and I can either do it by hand, or by a batch script. Batch script would be insanely easier.

I need the script to rename all of the files in a folder to have a surname + index. So the output would look like sample1.exe and sample was the surname, with the index as 1. I also need this index to increment after each file has been named to avoid duplicates. I've searched google but don't know enough to put one of these together. Does anybody have any suggestions?


Solution

  • If no filename will ever contain ! in the name, then

    @echo off
    setlocal enableDelayedExpansion
    set "surname=surname"
    set "index=0"
    for %%F in (*) do (
      set /a "index+=1"
      ren "%%F" "!surname!!index!%%~xF"
    )
    

    If a file name might contain ! then

    @echo off
    setlocal disableDelayedExpansion
    set "surname=surname"
    set "index=0"
    for %%F in (*) do (
      set "old=%%F"
      set "ext=%%~xF"
      set /a "index+=1"
      setlocal enableDelayedExpansion
      ren "!old!" "!surname!!index!!ext!"
      endlocal
    )