Search code examples
batch-filecmdfile-renamebatch-rename

How to bulk rename as name1.ext, name2.ext, name3.ext....... in all sub folders using cmd


I have tried the following code it shows operator missing. I tried in many ways but still something or the other error pops up.

@echo off
setlocal EnableDelayedExpansion

set var = " %cd% "
set i=1

forfiles /P %var % /S /M *.png /C "cmd /C set /a i=i+1 ren *.png Screenshot(!i!).png"

Someone please help me with this code I will be very glad ^_^

<-------------------------------------------------- Edited Later --------------------------------------------------------->

I am extremely sorry people but I wanted to
number the files in each folder separately starting from 1


Solution

  • The following code might work for you:

    @echo off
    setlocal EnableExtensions DisableDelayedExpansion
    rem // Initialise variables:
    set "NAME=Screenshot"
    set "PREV="
    rem // Loop through all matching files:
    for /F "delims= eol=|" %%F in ('
        dir /S /B /A:-D "*.png"
    ') do (
        rem // Store current file path and extension:
        set "FILE=%%~F" & set "PDIR=%%~dpF" & set "EXT=%%~xF"
        rem // Check whether parent directory path changed:
        setlocal EnableDelayedExpansion
        if /I not "!PDIR!"=="!PREV!" (
            endlocal
            rem // Parent directory path changed, so reset counter:
            set /A "COUNT=0"
        ) else endlocal
        rem // Increment index counter:
        set /A "COUNT+=1"
        rem // Toggle delayed expansion to not lose exclamation marks in file paths:
        setlocal EnableDelayedExpansion
        rem // Actually rename files:
        ECHO ren "!FILE!" "!NAME!(!COUNT!)!EXT!"
        endlocal
        rem // Store parent path of current file:
        set "PREV=%%~dpF"
    )
    endlocal
    

    After having tested the output, remove the upper-case ECHO command in front of ren!