0
@echo off
Setlocal enabledelayedexpansion

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

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

This renames .jpg having substring rename .Ref: How to rename file by replacing substring using batch in Windows Can anyone make me understand, How the For loop does this job? Additionally: is it possible to use a /f switch here, to get rid of Access Denied .

Community
  • 1
  • 1
Deb
  • 4,295
  • 5
  • 28
  • 38

2 Answers2

2

The for loop in your example will loop through each file ending with .jpg in the current directory.

Every iteration of the loop %%a will expand to the name of the current .jpg file.

The rename command then changes the name of %%a (current .jpg file) to a specified name, which is a modified version of the !File! variable.

"!File:%Pattern%=%Replace%!" - this is string manipulation - see DOS Tips. It will expand to the contents of the variable !File! where %Pattern% equals %Replace%.

So if you had the variable %test% which you have set to equal "Test_1_variable" and you run echo %test:_= % it will output Test 1 variable.

unclemeat
  • 4,831
  • 5
  • 24
  • 49
1

Test this: it uses a for /f so that the files aren't renamed twice.

@echo off
Setlocal enabledelayedexpansion

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

For /f "delims=" %%a in ('dir /b /a-d *.jpg ') Do (
Set "File=%%~na"
Ren "%%a" "!File:%Pattern%=%Replace%!%%~xa"
)
foxidrive
  • 39,095
  • 8
  • 48
  • 68