我试图根据目录名recursion地改变一些文件名,但是我失败了。 这是我迄今为止所做的:
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 )
这里是目录结构:
SubDir renamer.bat sub1 file1.c sub2 file2.c so on so forth
所有其他post都说%cd%
返回当前目录的名字,但是它返回类似于: c:\users\myusername\desktop\SubDir
,表示它返回batch file的目录名。 但是,正如你所看到的,我在batch file中使用了cd
命令,所以我希望它只返回sub1
, sub2
等…因此,我可以把文件名改成它们的目录名:
ren file1.c sub1.c
提前致谢。
编辑:答案
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) )
FOR /f "delims=" %%a IN ("%%~dpZ\.") DO ECHO(ren %%~nxZ %%~nxa-%%~nxZ
echo
新的名字….
在这种情况下,你应该使用延迟扩展。 你应该使用这个:
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" )
有关延迟扩展的更多信息,请参阅此