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
  • 5,163
  • 7
  • 30
  • 45

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
  • 5,029
  • 5
  • 28
  • 52
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
  • 40,353
  • 10
  • 53
  • 68