简体   繁体   中英

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?

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.

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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM