Batch rename file names, retain ext?

1

(Win10) In a batch file, how do I recursively rename filesnames in a folder? Not the extension.

e.g.

Files to rename: heavy.doc, bright.jpg, fast.docx, quiet.png, etc

Rename to: A1.*, A2.*, A3.*, A4.*, etc (where the .* retains the original ext)

Becomes: A1.doc, A2.jpg, A3.docx, A4.png, etc

Thanks!

narrator dru

Posted 2017-04-14T10:17:18.823

Reputation: 13

See this useful question and this how-to. Do you need to do this as part of a script? Why not use a standalone renaming program?

– simlev – 2017-04-14T10:37:46.230

The first appends a set string to a filename. Interesting, but not what I was after. The second does the job nicely, albeit with brackets. As for needing to do it in a batch-script, it would be nice to have a one-click solution that I can use regularly, and I love learning new ways to use such scripts. Cheers! – narrator dru – 2017-04-14T11:17:33.643

Answers

1

After a quick look at the reference page for for, I could come up with this:

@echo off & setlocal EnableDelayedExpansion 
set a=1
for /f "tokens=1,2 delims=." %%G in ('dir /b /s /A:-D') do (
    ren "%%G.%%H" "A!a!.%%H" 
    set /a a+=1
)

Update: it would be better to pass the initial folder as a parameter, so that the script itself can be placed anywhere and does not risk getting renamed itself.

@echo off & setlocal EnableDelayedExpansion 
set a=1
for /f "tokens=1,2 delims=." %%G in ('dir /b /s /A:-D %1') do (
    ren "%%G.%%H" "A!a!.%%H" 
    set /a a+=1
)

Explanation:

@echo off this avoids every command to be written to the console.

setlocal EnableDelayedExpansion this is needed in order for the a variable to actually increase.

set a=1 we create a counter variable called a and set its initial value to 1.

for /f loop against a list of filenames.

tokens=1,2 delims=. the filename is going to be split when a . is encountered. We are interested in the first two tokens resulting from this operation. Note: it is expected that filenames do not contain a dot, except between the basename and the extension.

%%G is the name of the first token (it's implicit that the second is going to be %%H).

in ('dir /b /s /A:-D %1') loop over the results of the dir command, that lists the files in the directory passed as a parameter %1 with the following options: /b clean output, /s include results from subdirectories, /A:-D only list files and not folder names.

ren "%%G.%%H" "A!a!.%%H" rename the filename (%%G.%%H reconstructs the original filename) to a constant A plus the variable a's current value, plus the original extension %%H.

set /a a+=1 increments the counter variable.

simlev

Posted 2017-04-14T10:17:18.823

Reputation: 3 184

Great script, simlev.. Thanks muchly.. will play with it! – narrator dru – 2017-04-14T11:34:08.203