32

I want to rename file name like "how-to-rename-file.jpg" to "how-to-reuse-file.jpg" by using a Windows batch file

I.e. I only want to replace one or two words in a file name.

3
  • 1
    Please add what you have tried. Also, we need more information. Commented Apr 21, 2013 at 7:25
  • Consider trying Bulk Rename Here. Commented Apr 21, 2013 at 7:27
  • @casperOne hmmm...a little too strict me thinks. Commented Nov 24, 2017 at 1:01

2 Answers 2

62
@echo off

Set "Filename=how-to-rename-file.jpg"
Set "Pattern=rename"
Set "Replace=reuse"

REM Call Rename "%Filename%" "%%Filename:%Pattern%=%Replace%%%"

Call Echo %%Filename:%Pattern%=%Replace%%%
:: Result: how-to-reuse-file.jpg

Pause&Exit

I give you other example for a loop of files:

UPDATE:

I've missed some things in the syntax 'cause fast-typing my last edit, here is the corrected code:

@echo off
Setlocal enabledelayedexpansion

Set "Pattern=rename"
Set "Replace=reuse"

For %%# in ("C:\Folder\*.jpg") Do (
    Set "File=%%~nx#"
    Ren "%%#" "!File:%Pattern%=%Replace%!"
)

Pause&Exit

PS: You can read here to learn more about substring: http://ss64.com/nt/syntax-substring.html http://ss64.com/nt/syntax-replace.html

Sign up to request clarification or add additional context in comments.

7 Comments

The second code is exactly what i need. Thank you sooo much for your help. Also thanks for providing me link to learn more about strings I found this link very informative :-)
Why did you use Set "File=%%~nx#" instead of a simple Set "File=%%#" ?
@Marco Demaio To introduce new users in the reserved For modifiers.
@ElektroStudios sorry, but what do you mean by "introduce new users"? What users?
Unfortunately that doesn't seem to work to replace 'special' characters such as ç or õ.
|
37

The code above doesn't rename the files - The paths are an issue and the source filename is incorrect.

This will work on files in the current folder - except those with ! in the names will be a problem.

@echo off
Setlocal enabledelayedexpansion

Set "Pattern=rename"
Set "Replace=reuse"

For %%a in (*.jpg) Do (
    Set "File=%%~a"
    Ren "%%a" "!File:%Pattern%=%Replace%!"
)

Pause&Exit

10 Comments

I know this is an old topic, but what should I add to define a folder instead of using the local folder?
Place pushd "c:\folder" above the loop, or use cd /d "c:\folder"
It works like a charm! Great stuff!
Just one note, I think Set "File=%%~a" can be replaced with Set "File=%%a" (with no ~) because the ~ is used with a parameter extension that you are not using. ss64.com/nt/syntax-args.html
This worked great. Now could you make it recursive on subfolders?
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.