【问题标题】:Grouping files together in folders created on a per-group basis将文件分组到按组创建的文件夹中
【发布时间】:2014-05-23 17:24:33
【问题描述】:

我有 16 个文件要组合在一起,这样每个文件夹就有 3 个文件(其余文件将放在单独的文件夹中)。本质上,这些文件有一个日期字符串,我想用它来对文件进行分组。例如,201301 是 2013 年 1 月。有没有办法创建批处理程序或以其他方式执行以下操作:

1) 创建与 201301 形式相同的所有字符串的列表。这可以通过选择一个起点(在本例中为标题中的 11 个字符)开始计数,然后计数到 5 来完成。

like this 是否符合要求?

2) 使用以下方式将这些字符串从小到大排序:

:startSort                            // Set our upper "array bound"
 set /a total=count-1

:RestartSort                          // Restart the sort from the beginning
 set /a count=1

:sortLoop
 set /a next=%count%+1                // Swap n and n+1
 call :swap %count% %next%
 set /a count=count+1
 if "%swapped%" == "true" goto :RestartSort // If the variables were swapped,
                                            // start again
 if "%count%" == "%total%" goto :output     // If we're done,
                                            // output the results
 goto :sortLoop                             // Back to the start to
                                            // swap the next two

3) 数到三,然后创建一个文件夹来存放这三个文件

4) 存储三个文件

5) 继续,直到没有更多文件存在

我对这个设置的唯一问题是,当它到达最后一个没有其他文件要分组的文件时,它可能不知道该怎么做。有没有办法让它解决这个问题——它知道它已经到了列表的末尾?

作为参考,文件名的格式为 12345_ABCDE_20130101_20130101,文件夹名称可以简单地类似于 201301-201303(使用相同的示例值)。

【问题讨论】:

  • @Alex 我一直在四处寻找,看看是否已经将“排序”代码之类的部分放在了某个地方。我主要关心的是如何创建一个将文件名中的这些“字符串”识别为数字的数组。
  • 你能显示示例文件名和建议的文件夹名称吗?
  • @Alex 没问题,我更新了我原来的问题。

标签: windows batch-file cmd


【解决方案1】:

代码示例:

@ECHO OFF &SETLOCAL disableDelayedExpansion
SET /a Counter=0
SET /a FilesPerFolder=3
FOR /f "delims=" %%a IN ('DIR /b /a-d /on "%cd%\test\*"') DO (
    SET /a Test=Counter%%FilesPerFolder
    SET /a TargetFolder=Counter/FilesPerFolder
    SETLOCAL enableDelayedExpansion
    MD "%cd%\test\Folder!TargetFolder!" 2>nul
    MOVE "%cd%\test\%%~a" "%cd%\test\Folder!TargetFolder!" >nul
    ENDLOCAL
    SET /a Counter+=1
)

【讨论】:

  • 谢谢!我知道这可能是多余的,但是您是否可以逐行或部分解释代码的作用?我对批处理很陌生。