Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to rename file by replacing substring using batch in Windows [closed]

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.

like image 677
Varun Avatar asked Apr 21 '13 07:04

Varun


People also ask

Is there a way to batch rename files to lowercase?

rename "%f" "%f" - rename the file with its own name, which is actually lowercased by the dir command and /l combination.

How do I batch rename files sequentially?

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 batch rename file extensions in Windows?

How to batch rename extensions. Navigate to the folder containing the files you want. Once there, launch command prompt from the folder menu by holding down shift and right clicking on an empty space. Once in command prompt, you can now use the “ren” (for rename) command to rename for example, .


2 Answers

@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

like image 85
ElektroStudios Avatar answered Sep 22 '22 08:09

ElektroStudios


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 
like image 40
foxidrive Avatar answered Sep 20 '22 08:09

foxidrive