Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rename all files in a directory with a Windows batch script

How would I write a batch or cmd file that will rename all files in a directory? I am using Windows.

Change this:

750_MOT_Forgiving_120x90.jpg
751_MOT_Persecution_1_120x90.jpg
752_MOT_Persecution_2_120x90.jpg
753_MOT_Hatred_120x90.jpg
754_MOT_Suffering_120x90.jpg
755_MOT_Freedom_of_Religion_120x90.jpg
756_MOT_Layla_Testimony_1_120x90.jpg
757_MOT_Layla_Testimony_2_120x90.jpg

To this:

750_MOT_Forgiving_67x100.jpg
751_MOT_Persecution_1_67x100.jpg
752_MOT_Persecution_2_67x100.jpg
753_MOT_Hatred_67x100.jpg
754_MOT_Suffering_67x100.jpg
755_MOT_Freedom_of_Religion_67x100.jpg
756_MOT_Layla_Testimony_1_67x100.jpg
757_MOT_Layla_Testimony_2_67x100.jpg
like image 809
Blainer Avatar asked Feb 21 '12 18:02

Blainer


People also ask

How do I batch rename all files in a folder?

You can press and hold the Ctrl key and then click each file to rename. Or you can choose the first file, press and hold the Shift key, and then click the last file to select a group.

How do I rename files in bulk CMD?

Highlight each file which you want to rename. Press Ctrl+A to highlight them all, if not, then press and hold Ctrl and click on each file you want to highlight. Once all the files are highlighted, right-click on the first file and click on “Rename” (press F2 to rename the file without making more actions).


1 Answers

A FOR statement to loop through the names (type FOR /? for help), and string search and replace (type SET /? for help).

@echo off
setlocal enableDelayedExpansion
for %%F in (*120x90.jpg) do (
  set "name=%%F"
  ren "!name!" "!name:120x90=67x100!"
)


UPDATE - 2012-11-07

I've investigated how the RENAME command deals with wildcards: How does the Windows RENAME command interpret wildcards?

It turns out that this particular problem can be very easily solved using the RENAME command without any need for a batch script.

ren *_120x90.jpg *_67x100.*

The number of characters after the _ does not matter. The rename would still work properly if 120x90 became x or xxxxxxxxxx. The important aspect of this problem is that the entire text between the last _ and the . is replaced.

like image 144
dbenham Avatar answered Oct 09 '22 02:10

dbenham