1

I am trying to recursively change some file names according to their directory name but I am failed. Here is what I have done so far:

for /r %1 %%Z in (*.c) do ( echo ==== rem Change to the directory of .c file echo cd /d "%%~dpZ" cd /d "%%~dpZ" rem Change the file's name with its directory name with .c extension ren %%~nxZ %cd%.c ) 

And here is the directory structure:

SubDir renamer.bat sub1 file1.c sub2 file2.c so on so forth 

All the other posts say that using %cd% returns the current directory's name, however it returns something like that: c:\users\myusername\desktop\SubDir,means it returns the batch file's directory name. However, as you can see, I use cd command in the batch file, so I want it to returns only sub1, sub2, etc... Thus, I can able to change the file names into their directory's name:

ren file1.c sub1.c 

Thanks in advance.

EDIT: Answer

setlocal EnableDelayedExpansion for /r %1 %%Z in (*.c) do ( echo ==== rem Change to the directory of .c file echo cd /d "%%~dpZ" cd /d "%%~dpZ" rem Change the file's name with its directory name with .c extension FOR /f "delims=" %%a IN ("%%~dpZ\.") DO (ren %%~nxZ %%~nxa.c) ) 
1
  • Please do not provide a solution by editing the question, post it as an answer because that is what it is... Commented Mar 22, 2016 at 9:46

2 Answers 2

2
 FOR /f "delims=" %%a IN ("%%~dpZ\.") DO ECHO(ren %%~nxZ %%~nxa-%%~nxZ 

to echo the new name....

Sign up to request clarification or add additional context in comments.

Comments

0

You should use delayed expansion in this case. You should use this:

setlocal EnableDelayedExpansion for /r %1 %%Z in (*.c) do ( echo ==== rem Change to the directory of .c file echo cd /d "%%~dpZ" cd /d "%%~dpZ" rem Change the file's name with its directory name with .c extension for /f "delims=" %%A in ("!CD!") do ren "%%~nxZ" "%%~nxA.c" ) 

For more information about delayed expansion, see this

7 Comments

It still applies wrong command. ren file1.c c:\bla bla\sub1.c I need ren file1.c sub1.c
The system cannot find the file C:\Users\myusername\Desktop\SubDir\sub1. says. still dont work.
@WhoCares did you use the quotes around !CD!?
Directly copied what you told. So yes.
Can you try placing echo before ren and tell me what the output is? I also edited the quotes in later, that's why I asked.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.