Renaming in command prompt

Posted on

QUESTION :

I have images with filenames like 0034343.jpg and I want to remove the leading zeros, leaving 34343.jpg as the new filename.

How can I do this in the command prompt? I tried REN 00*.jpg *.jpg, but it didn’t work.

ANSWER :

You should be able to start with:

@setlocal enableextensions enabledelayedexpansion
@echo off
for /f "delims=*" %%a IN ('dir /b 00*.jpg') do (
    set file=%%a
    set newfile=!file:~2!
    echo move !file! !newfile!
)
endlocal

This will, as it stands, simply echo the move command. Remove the echo once you’ve finished testing. And keep in mind this may not work as expected if your file names have spaces in them.

Stepping through it bit by bit:

  • The setlocal enables certain cmd.exe extensions, chief here being the ability to do delayed expansion of environment variables inside for loops.
  • The for loop runs the cmd dir /b 00*.jpg, doing one iteration per file (setting %%a to the file name).
  • The first set simply saves the filename into a variable. The second is a substring operation starting at the third character.
  • The move will rename the file.

You can examine the various commands by entering help commands at the command line:

setlocal /?
set /?
for /?
set /?

Try this:

for %i in (*.jpg) do (
    set filename=%~nxi
    set newname=%filename:~2%
    ren !filename! !newname!
)

This will just strip two characters off the beginning of every file name. Delayed expansion must be enabled. Might need to do cmd.exe /v:on first on XP.

Leave a Reply

Your email address will not be published.