0

Can anyone advise me where I am going wrong with this? I have some file names that contain XXX XXX_Layer_XXX and I'm trying to replace to XXX XXX_Layer__XXX

My attempt so far was:

ren  "*Layer_*.*"  "*Layer__*.*"

But that does not seem to be working as expected!

phuclv
  • 30,396
  • 15
  • 136
  • 260
Martyn
  • 111

2 Answers2

1

It should be much easier in PowerShell

Get-ChildItem *Layer_* | Rename-Item -NewName { $_.Name -creplace '_Layer_', '_Layer__' } -WhatIf

Aliased version:

ls *Layer_* | ren -Ne { $_.Name -creplace '_Layer_', '_Layer__' } -wi

After confirming the new names are correct just remove -WhatIf / -wi to do a real rename

In cmd the rename command does a greedy replacement in the target if it sees a * so your solution won't work. See How does the Windows RENAME command interpret wildcards?. You'll need to replace the string yourself. Something like this

@echo off
setlocal enabledelayedexpansion

for %%d in (Layer) do ( set "name=%%d" echo ren "!name!" "!name:Layer=_Layer__!" )

The replacement is this part !name:_Layer_=_Layer__!. The syntax is %variablename:text_to_find=text_to_replace%

phuclv
  • 30,396
  • 15
  • 136
  • 260
0

My previous answer tried to use the ren command and failed, because this command only does a very primitive string matching. Most importantly, it cannot replace a string with a longer one.

To prevent others from making the same mistake, here is an explanation (not an answer).

If the command is written as:

ren SourceMask TargetMask

then any character in TargetMask causes the pointer into SourceMask to advance by one position.

So, if we are renaming the file 1234.567 by the following command:

ren *2*.* *2X*.*

the result will be 12X4.567. It will not be the naively expected 12X34.567.

The reason is that TargetMask is handled here like this:

*2 - matches up to and including 2, adding to target : 12
X - matches itself AND advances one position so skipping 3, adding to target : X
*. - matches up to and including the point, adding to target : 4.
* - matches the extension part, adding to target : 567

Conclusion: The ren command should be avoided when replacing strings of unequal lengths.

The way ren works is described in a very complete manner in the post
How does the Windows RENAME command interpret wildcards?.

harrymc
  • 498,455