vvmul
vvmul

Reputation: 422

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?

Upvotes: 0

Views: 264

Answers (2)

dbenham
dbenham

Reputation: 130819

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"

Upvotes: 1

Magoo
Magoo

Reputation: 80023

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

Within a block statement (a parenthesised series of statements), the entire block is parsed and then executed. Any %var% within the block will be replaced by that variable's value at the time the block is parsed - before the block is executed - the same thing applies to a FOR ... DO (block).

Hence, IF (something) else (somethingelse) will be executed using the values of %variables% at the time the IF is encountered.

Two common ways to overcome this are 1) to use setlocal enabledelayedexpansion and use !var! in place of %var% to access the changed value of var or 2) to call a subroutine to perform further processing using the changed values.

Within a batch file, the loop-control variable references require to have the % doubled.

Upvotes: 2

Related Questions