Search code examples
windowsbatch-filecommand-linebatch-rename

Renaming files in Windows using FOR


The task is to rename five random files to renamed1.ren, renamed2.ren, ..., renamed5.ren using the command line. Here is what I've come to:

set i=1
for /f "tokens=*" %f in ('dir /b') do (
ren %f renamed%i%.ren
set /a i+=1)

I expected i to be incremented in every iteration, but that didn't work. What can I change?


Solution

  • Here is a one liner that does not require delayed expansion.

    From the command line:

    for /f "tokens=1* delims=:" %A in ('dir /b^|findstr /n "^"') do @ren "%B" "renamed%A.ren"
    

    Within a batch script

    @echo off
    for /f "tokens=1* delims=:" %%A in ('dir /b^|findstr /n "^"') do ren "%%B" "renamed%%A.ren"