复制最近创建的15个文件

时间:2019-06-08 19:38:19

标签: batch-file

我有Microsoft Batch文件,在代码的一部分中,我从文件夹(RootDir)复制到另一个(CopyDir)最后创建的文件,该文件具有特定的命名约定。但是现在我需要复制最后15个相同类型的文件。 你能帮我吗?

set lastmod=
pushd %RootDir%
for /f "tokens=*" %%a in ('dir _UnipolSai_Outlier_Daily_Report_Agg1__UnipolSai_Outlier_Daily_Report_Agg1*.gz /b /o-d /a-d 2^>NUL') do set lastmod=%%a & goto :xx
:xx
if "%lastmod%"=="" echo Could not locate files.&goto :eof
:::
copy /Y "%lastmod%" "%CopyDir%"

1 个答案:

答案 0 :(得分:0)

@ECHO OFF
SETLOCAL
SET "sourcedir=."
SET /a required=15
:: remove variables starting #
FOR  /F "delims==" %%a In ('set # 2^>Nul') DO SET "%%a="

FOR /f "delims=" %%a IN ('dir /b /a-d /o-d "%sourcedir%\*" ') DO (
 SET "#0=Y"
 FOR /L %%b IN (1,1,%required%) DO IF DEFINED #0 IF NOT DEFINED #%%b (
  SET "#0="
  SET "#%%b=%%a"
  ECHO process "%%a"
  IF defined #%required% GOTO done
 )
)
SET "#0="
:done
SET #
:: remove variables starting #
FOR  /F "delims==" %%a In ('set # 2^>Nul') DO SET "%%a="

GOTO :EOF

您需要根据自己的情况更改sourcedir的设置。

您显然对dir选项很熟悉,所以我将保留这个问题。

此方法清除以#开头的所有变量,然后使用#0作为标志来确定他的文件名是否已处理。首先将其设置为 something ,然后检查#1 ..#15。

如果未定义# n ,则将其设置为正在处理的数据行并清除#0,因此只有一个# n 将是{{1 }}。我只是选择set找到的文件名-显然,这可以是您选择的任何处理。

设置了echo后,终止循环-额外的好处是,找到的每个值都可以用作#15

相关问题