user3657108
user3657108

Reputation: 11

Batch file rename - find and replace

I'm trying to write a Windows batch file to rename a set of files based on their original name. What I essentially want to do is find text within a file name and replace it with other text. For example, if the files had the naming structure "Family Christmas 001.jpg" I might want to change it to "Photos - Xmas 001.jpg". ie replace "Family Christmas" with "Photos - Xmas". This is just an example.

I've found a piece of code from a user of this site, dbenham, that does almost exactly what I'm after. In this example he's replacing "120x90" in a filename to "67x100" Here's the code:

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

Can anyone help me adapt this code to make it handle spaces in the file name?

Thanks

Upvotes: 1

Views: 1504

Answers (1)

zb226
zb226

Reputation: 10538

All you're missing is quotes within the FOR statement - to follow your example:

@echo off
setlocal enableDelayedExpansion
for %%F in ("Family Christmas*.jpg") do (
  set "name=%%F"
  ren "!name!" "!name:Family Christmas=Photos - Xmas!"
)

Upvotes: 1

Related Questions