批量抓取文件名并重命名

时间:2015-03-30 07:22:06

标签: batch-file batch-rename

我有一个文件名如下: Summary_20022015.xlsx

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

1)FROM:Summary_20022015.xlsx

收件人:Summary_20150220.xlsx

2)FROM:Summary_25022015.xlsx

收件人:Summary_20150225.xlsx

原文是(文件名)_DDMMYYYY.xlsx

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

结果是(文件名)_YYYYMMDD.xlsx

因为我在文件夹中有多个文件。 手动重命名所有这些都很麻烦。

1 个答案:

答案 0 :(得分:0)

这适用于我的测试文件。在运行脚本之前,您需要设置文件所在的位置。另外,在运行之前在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