0

I want to, for example, replace all -v1 parts in every filename for -v2. It's almost working, but the access is denied because the files are being used by the cmd process itself during execution. My current code is:

for /f "delims=" %%a in ('dir /a-d /b *-v1*') do ren "%%a" "%%a:-v1=-v2"

Any suggestions? :)

EDIT:

I've also tried for /r %%i in ("*-v1*") do ren "%%~nxi" "%%~nxi:-v1=-v2" and it finds the files and uses the correct rename value, but still outputs that it can't access the file because it is in use by another process. I'm sure that process is the cmd.exe itself, because after I close the command prompt, I can change the filenames manually without any problems.

I also tried by writing the current filenames to a temporary .txt file with the idea that the files I want to rename aren't used by any command. Then read the file with the type command within a for loop to rename each file, but same thing.

It's quite frustrating, any help is appreciated :)

Bob Vandevliet
  • 213
  • 3
  • 14

1 Answers1

2

substring substituion doesn't work with for variables (%%a). Use a "normal" variable and delayed expansion:

@echo off
setlocal enabledelayedexpansion
for /f "delims=" %%a in ('dir /a-d /b *-v1*') do (
  set filename=%%a
  ren "%%a" "!filename:-v1=-v2!"
)
Stephan
  • 53,940
  • 10
  • 58
  • 91
  • Thank you! It works. I was almost getting a headache :P Didn't know substring substitution doesn't work on (`%%i`) kind of variables :) And it needs the `enable enabledelayedexpansion` to work as well, didn't know that either. – Bob Vandevliet Feb 08 '18 at 16:40