代码之家  ›  专栏  ›  技术社区  ›  marcus chan

批量抓取文件名和重命名

  •  1
  • marcus chan  · 技术社区  · 10 年前

    我有一个文件名如下: 总结_20022015.xlsx

    我想做的是使用批处理文件重命名。

    1) 发件人:Summary_20022015.xlsx

    收件人:Summary_20150220.xlsx

    2) 发件人:Summary_25022015.xlsx

    收件人:Summary_20150225.xlsx

    原始文件为(文件名)_DDMYYYY.xlsx

    我需要的是保留(文件名)并改为YYYYMMDD。 只需使用实际文件名重新排列。

    结果为(文件名)_YYYYMMDD.xlsx

    因为文件夹中有多个文件。 手动重命名所有文件会很麻烦。

    1 回复  |  直到 10 年前
        1
  •  0
  •   SomethingDark    10 年前

    这对我的测试文件有效。在运行脚本之前,需要设置文件的位置。此外,将 echo ren 语句,以便确保获得所需的输出。

    @echo off
    setlocal enabledelayedexpansion
    
    :: While it's a good idea to never have spaces in your paths, sometimes it's unavoidable, so use quotes
    :: The quotes being where they are will preserve the spaces without including the quotes in the value
    set source_files="C:\path\to\where\the files\are"
    
    :: Go into the %source_files% path, but remember where we were for later
    pushd %source_files%
    
    :: The /b option will only process the file names and not the other things that appear with dir output
    :: Split each filename on underscores and periods
    :: %%A is going to be the word Source and %%C is going to be xlsx
    for /F "tokens=1-3 delims=_." %%A in ('dir /b') do (
        set base_date=%%B
        set date_day=!base_date:~0,2!
        set date_mon=!base_date:~2,2!
        set date_year=!base_date:~4,4!
    
        ren %%A_%%B.%%C %%A_!date_year!!date_mon!!date_day!.%%C
    )
    
    :: Go back to the path we were in before the script ran
    popd