File rename batch

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

Post Reply
Message
Author
cpatin
Posts: 2
Joined: 13 Aug 2013 21:53

File rename batch

#1 Post by cpatin » 13 Aug 2013 22:14

I'm trying to create a batch in which I rename all the files in one directory so that they have identical names except for the last character. For example, after it is processed I'd like to see

file1.txt
file2.txt
file3.txt ... etc.

I'm trying to use a variable that gets incremented for each iteration. However, the result is that only one file gets renamed and the others don't because rename is using the previously constructed (and used) file name. My variable is getting incremented, but only the initial setting of this variable is ever used in the rename expression. Can anyone tell me where I went wrong? My script is as follows:

cd documents
set /a $_count=1
for %%i in (*) do (rename %%i file%count%.txt & set /a $_count=count+1)

cpatin
Posts: 2
Joined: 13 Aug 2013 21:53

Re: File rename batch

#2 Post by cpatin » 13 Aug 2013 22:38

Typo in below, should be

cd documents
set /a $_count=1
for %%i in (*) do (rename %%i file%$_count%.txt & set /a $_count=$_count+1)

foxidrive
Expert
Posts: 6031
Joined: 10 Feb 2012 02:20

Re: File rename batch

#3 Post by foxidrive » 14 Aug 2013 00:12

This should work.

Code: Select all

@echo off
setlocal enabledelayedexpansion
set count=0
for /f "delims=" %%a in ('dir *.* /b /a-d ') do (
set /a count+=1
rename "%%a" "file!count!.txt"
)

Post Reply