使用批处理文件重命名/更新具有当前日期的任何日期字符串

时间:2015-06-09 16:50:13

标签: batch-file

到目前为止,我有一个批处理文件,用于重命名括号中更新日期字符串的文件。这工作正常,但日期可以是任何数字。如何让批处理更新括号中包含的任何日期字符串。

echo on
for /f "skip=1" %%x in ('wmic os get localdatetime') do if not defined MyDate set MyDate=%%x
set today=%MyDate:~0,4%-%MyDate:~4,2%-%MyDate:~6,2%


set "_year=%MyDate:~0,4%"
set "_month=%MyDate:~4,2%"
set "_day=%MyDate:~6,2%"

REN C:\Users\xyz125\Documents\Erics's Docs\scripts\"test file (20150112).txt" "test file (%_year%%_month%%_day%).txt"

pause

2 个答案:

答案 0 :(得分:0)

尝试dir/b | Findstr /r "([0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9])"

这导致以下文件this (20150609)something.txt,并且该文件夹还包含一个名为test(1234)else.txt的文件,由于正则表达式正在查找8个数字而不是4,因此找不到该文件。该模式将是dir / b | Findstr / r"([0-9] [0-9] [0-9] [0-9])"`

这篇文章帮助Piped Variable Into FINDSTR w/ Regular Expressions and Escaped Double Quotes你可以做类似的事情,并用你希望文件重命名的字符串设置一个变量。

- 编辑添加关于字符串连接的注释see here

另见Generate unique file name with timestamp in batch script

的答案

答案 1 :(得分:0)

@4317867.  Sorry about that.  For some reason I could not edit the code while pasting a response comment. Im not familiar with reg express. Would it look anything close to this: 



echo ON
for /f "skip=1" %%x in ('wmic os get localdatetime') do if not defined MyDate set MyDate=%%x
set today=%MyDate:~0,4%-%MyDate:~4,2%-%MyDate:~6,2%


set "_year=%MyDate:~0,4%"
set "_month=%MyDate:~4,2%"
set "_day=%MyDate:~6,2%"

 C:\Batch | Findstr /r "([0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9])"

REN "C:\Batch\ | Findstr /r (%_year%%_month%%_day%).txt"

rem ^

pause