Batch rename file using for loop

让人想犯罪 __ 提交于 2020-01-05 06:44:05

问题


I am trying to use a for loop to rename a file

::@Echo Off
setlocal enableDelayedExpansion
::Set Date
set mydate=%DATE:~10,4%%DATE:~4,2%%DATE:~7,2%
::Rename file
for %%F in (D:\Data\*.bak) do (
    ren %%F D:\Data\prod_live_Full_%mydate%0000.Lts.bak
)

I keep getting invalid command error. Any help is appreciated.


回答1:


When modifying files in a directory use a static file list from dir instead of a dynamic file list from for. Otherwise, you will get stuck in an infinite loop.

@echo Off
setlocal
set "mydate=%DATE:~10,4%%DATE:~4,2%%DATE:~7,2%"
pushd "D:\Data\" && for /f "delims=" %%A in ('dir /a-d /b *.bak') do (
    ren "%%~fA" "prod_live_Full_%mydate%0000.Lts.bak"
)
popd
endlocal
exit /b 0

The error was caused by your second parameter to the ren command. It is only expecting a new file name, not a full path and file name. The ren command cannot move files.




回答2:


I don't know your date format, but if the logic of date cut is not correct (in my pc, in spanish, it doesn't work) the mydate variable can contain a slash, which is not allowed in a file name.

If there are more than one file, ren will fail, as all the rename operations try to use the same file name.



来源:https://stackoverflow.com/questions/19453995/batch-rename-file-using-for-loop

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!