Windows – Renaming in command prompt

command linewindows

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.

Best 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!

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 /?