根据文件名中的日期创建批处理文件并移动文件

时间:2018-06-11 19:37:34

标签: batch-file

我有大量的excel文件,文件名都以时间戳结尾,如下所示:

examplefile_2018_08_24_110222.xlsx

我想根据时间戳的月份和年份移动所有这些文件,但我希望文件夹名称是上个月。因此,对于上面的示例,我想创建一个名为July2018的文件夹,并将该文件移动到该文件夹​​中。是否可以使用批处理文件执行此操作?

2 个答案:

答案 0 :(得分:2)

我认为这将做你需要它做的事情。我添加了一些评论,如果您不理解代码行,请告诉我。

@ECHO OFF

REM get a list of the files
FOR %%F IN (*.xlsx) DO (
    REM GET 2nd, 3rd and 4th parts of file name: examplefile_2018_08_24_110222.xlsx
    FOR /F "tokens=2,3,4 delims=_" %%G IN ("%%~F") DO (
        REM GET previous month and/or year
        FOR /F "delims=" %%J IN ('powershell "(Get-Date %%H/%%I/%%G).AddMonths(-1).ToString('MMMMyyyy')"') DO (
            REM make the directory
            md "%%J" >nul 2>&1
            REM move the file
            move "%%~F" "%%J\"
        )
    )
)

答案 1 :(得分:0)

您应该能够关注上一个问题:How to rename file by replacing substring using batch in Windows

这个问题更像是一个"发现和替换"批处理文件问题,但可能会很好。在您的情况下,您似乎可能想要查找和替换:

2018_08July2018

带有2018_09

August2018

这里的问题是所需的案例和循环数量。

例如,这将是3个月:

@echo off
Setlocal enabledelayedexpansion

Set "Location=C:\Users\Example"

Set "Pattern=2018_08"
Set "Replace=July2018"

For %%# in ("%Location%\*.xlsx") Do (
    Set "File=%%~nx#"
    Ren "%%#" "!File:%Pattern%=%Replace%!"
)

Set "Pattern=2018_09"
Set "Replace=August2018"

For %%# in ("%Location%\*.xlsx") Do (
    Set "File=%%~nx#"
    Ren "%%#" "!File:%Pattern%=%Replace%!"
)

Set "Pattern=2018_10"
Set "Replace=September2018"

For %%# in ("%Location%\*.xlsx") Do (
    Set "File=%%~nx#"
    Ren "%%#" "!File:%Pattern%=%Replace%!"
)

Pause&Exit

请注意,C:\ Users \ Example将替换为您想要的文件夹。

相关问题