我已经构建了2个批处理文件,每个文件都有其自己的功能:
将文件名更改为今天的日期
SET src_folder="C:\DIR_A\"
SET tar_folder="C:\DIR_A\DIR_B"
for /f %%a IN ('dir "%src_folder%" /b') do REN *.xml %time:~0,2%%time:~3,2%%time:~6,2%_%date:~-10,2%%date:~-7,2%%date:~-4,4%.xml
pause
第二个:
将文件从DIR_A移至DIR_B
SET src_folder="C:\DIR_A\"
SET tar_folder="C:\DIR_A\DIR_B"
for /f %%a IN ('dir "%src_folder%*.xml" /b') do move %src_folder%\%%a %tar_folder%
pause
我的问题是:如何将它们在一个循环中合并?
第二个问题是命名循环。该循环仅命名第一个XML文件,并说该名称已存在。因此,这是正确的,是否有使其在再次命名之前暂停的原因,所以文件具有不同的名称吗?
答案 0 :(得分:1)
简单:要使用多个命令,请使用代码块:
for %%a IN ("%src_folder%") do (
echo RENAME %%a
echo COPY %%a
)
注意:请记住,您可能需要使用delayed expansion(虽然在此示例中不是)
应用于您的代码:
@echo off
setlocal enabledelayedexpansion
SET src_folder="C:\DIR_A\"
SET tar_folder="C:\DIR_A\DIR_B"
for %%a IN ("%src_folder%*.xml") do (
REN "%%a" !time:~0,2!!time:~3,2!!time:~6,2!_%date:~-10,2%%date:~-7,2%%date:~-4,4%.xml
move "%src_folder%\%%a" "%tar_folder%"
timeout 1 >nul
)
注意:这里需要使用time
变量进行延迟扩展(至少)。考虑也延迟date
(将是“最佳实践”)
或者:首先重命名所有文件,然后一次性复制它们:
@echo off
setlocal enabledelayedexpansion
SET src_folder="C:\DIR_A\"
SET tar_folder="C:\DIR_A\DIR_B"
for %%a IN ("%src_folder%*.xml") do (
REN "%%a" !time:~0,2!!time:~3,2!!time:~6,2!_%date:~-10,2%%date:~-7,2%%date:~-4,4%.xml
timeout 1 >nul
)
move "%src_folder%\*.xml" "%tar_folder%\"
答案 1 :(得分:1)
最简单的方法是一次性完成,而无需重命名,只需使用新名称移动它们即可。
@echo off
for %%a IN (*.xml) do (
move "%source_folder%\%%a" "%tar_folder%\%time:~0,2%%time:~3,2%%time:~6,2%_%date:~-10,2%%date:~-7,2%%date:~-4,4%.xml"
)
pause
其他方法:
@echo off
setlocal enabledelayedexpansion
for /f %%a IN ('dir /b /a-d "%src_folder%\*.xml"') do (
set "myren=%time:~0,2%%time:~3,2%%time:~6,2%_%date:~-10,2%%date:~-7,2%%date:~-4,4%.xml"
ren "%%a" "!myren!"
move "%src_folder%\!myren!" "%tar_folder%"
)
pause
或者没有delayedexpansion
:
@echo off
for /f %%a IN ('dir /b /a-d "%src_folder%\*.xml"') do (
move "%%a" "%tar_folder%"
ren "%tar_folder%\%%a" "%time:~0,2%%time:~3,2%%time:~6,2%_%date:~-10,2%%date:~-7,2%%date:~-4,4%.xml"
)
pause
甚至:
@echo off
for /f %%a IN ('dir /b /a-d "%src_folder%\*.xml"') do (
ren "%source_folder%\%%a" "%time:~0,2%%time:~3,2%%time:~6,2%_%date:~-10,2%%date:~-7,2%%date:~-4,4%.xml"
)
move /Y "%src_folder%\*.xml" "%tar_folder%"
pause
最简单,一次完成: