问题
Is it possible for a batch file to rename all files in a directory by appending the date of previous weekday to the end of the filename?
for example, if i ran it on Monday 2/25/12, it would add "_022213" to the end of the filenames in the directory.
Thanks...
回答1:
Here you go.
@echo off
setlocal enabledelayedexpansion
echo wd = Weekday^(Date^(^), vbSunday^)>yesterday.vbs
echo if wd ^< 3 then dif = -1 - wd else dif = -1 >>yesterday.vbs
echo d = dateadd^("d", dif, Date^(^)^)>>yesterday.vbs
echo wscript.echo DatePart^("yyyy",d^) ^& " " ^& DatePart^("m", d^) ^& " " ^& DatePart^("d", d^) >>yesterday.vbs
for /f "tokens=1-3" %%I in ('cscript /nologo yesterday.vbs') do (
set year=%%I
if %%J leq 9 (set month=0%%J) else set month=%%J
if %%K leq 9 (set day=0%%K) else set day=%%K
)
del yesterday.vbs
set yesterday=%month%%day%%year:~-2%
for %%I in (*) do (
set base=%%~nI
echo !base:~-7!| findstr "^_[0-9]*$" >NUL && set base=!base:~0,-7!
ren "%%I" "!base!_!yesterday!%%~xI"
)
There's no native function in Windows batch scripting that will let you perform math on dates. VBscript has some nifty date math functions though. DateAdd will let you add or subtract by the year, the quarter, the month, or several other intervals. "w" specifies work day. More info. Update: apparently "w" doesn't mean what it seems like it should mean. Script updated to perform the math manually.
You can borrow from vbscript by echoing the vbscript to a .vbs file, then capturing the output of cscript /nologo vbsfile
with a for
loop. See how that works?
Then just piece together [basename]_[yesterday with slashes stripped][extension]
.
回答2:
For a batch only solution see https://gist.github.com/DavidRuhmann/4666270
Here is how to use the batch script method in the link.
@echo off
if /i "%Date:~0,3%"=="Sun" ( call :DaysAgo 2 ) else (
if /i "%Date:~0,3%"=="Mon" ( call :DaysAgo 3 ) else ( call :DaysAgo 1 )
)
echo %Year% %Month% %Day%
来源:https://stackoverflow.com/questions/15011081/rename-file-with-previous-weekday