【问题标题】:Compare dates in Batch File from File Name从文件名比较批处理文件中的日期
【发布时间】:2015-03-25 15:11:44
【问题描述】:

如果文件名中的日期时间已过,需要一个脚本来移动文件。

这是我尝试过的,但它总是移动所有文件。

@ECHO OFF
set hr=%time:~0,2%
if "%hr:~0,1%" equ " " set hr=0%hr:~1,1%
SET CurrTime=%date:~-4,4%%date:~-10,2%%date:~-7,2%%hr%%time:~3,2%%time:~6,2%

FOR /F "tokens=*" %%G IN ('dir /b E:\FileLoc\A_ChangePrice_*txt') DO (
    SET "LL=%%G"
    SET CurrFileTime=%LL:~16,-4%
    SET "FileTime=%%CurrFileTime%%"
    CALL ECHO %CurrTime%
    CALL ECHO %FileTime%

    IF %CurrTime% GTR %FileTime% (MOVE E:\FileLoc\%%G CALL ECHO F:\PriceChanges\%%G)
)

当前时间=20150325104003 文件时间=20160425192500

我发现这个脚本有 2 个问题。

  1. 脚本第一次运行 FileTime 为空?!
  2. 即使 FileTime 更大,它也会移动文件。

可能有比这更简单的解决方案,我愿意提供建议。

提前致谢。

【问题讨论】:

    标签: date batch-file math cmd compare


    【解决方案1】:

    这行得通。如果您有更清洁的解决方案,将设置正确答案。

    @ECHO OFF
    SETLOCAL ENABLEDELAYEDEXPANSION
    
    set hr=%time:~0,2%
    if "%hr:~0,1%" equ " " set hr=0%hr:~1,1%
    SET CurrDateTime=%date:~-2,4%%date:~-10,2%%date:~-7,2%%hr%%time:~3,2%
    
    FOR /F "tokens=*" %%G IN ('dir /b E:\FileLoc\A_ChangePrice_*txt') DO (
        SET "FileName=%%G"
        SET /a "FileDateTime=!FileName:~16,-4%!"
        IF %CurrDateTime% GTR !FileDateTime! (CALL MOVE E:\FileLoc\%%G CALL ECHO F:\PriceChanges\%%G)
    )
    ENDLOCAL
    

    【讨论】:

    • 您发现了delayedexpansion,这解释了file time empty 问题。另一个问题是gtr 对 32 位有符号值起作用,并且您的值太大,因此转换会产生不正确的结果。您需要强制进行字母比较(假设两个字符串长度相等),您可以通过在变量之前或之后包含几乎任何常量字母字符来完成,例如IF q%CurrTime% GTR q!FileTime!...
    • 谢谢@Magoo 我从日期中删除了 4 位数字,以便它可以适合 32 位有符号值。现在日期看起来像 1503251233 并且有效。我还应该强制进行字母比较吗?
    • 不会有坏处,但也没有优势。
    【解决方案2】:

    很好地解决了您的问题。前段时间我尝试过类似的东西,但是看到你的代码让我走上了正确的道路(谢谢),我重新发明了你的代码(几乎相同,除了我选择了不同的方法来设置当前的datetime)是以下。我使用不同的pathfilename 结构对其进行了测试,它似乎有效。就像我说的,它几乎相同,但扩展修饰符更少。

    @echo off
    setlocal enabledelayedexpansion
    
    for /f "tokens=1-3 delims=/ " %%i in ('date /t') do (set currdate=%%k%%j%%i)
    for /f "tokens=1-2 delims=:. " %%i in ("%time%") do (set currtime=%%i%%j)
    set currdt=%currdate:~2%%currtime%
    
    for /f "tokens=*" %%i in ('dir /b C:\XXX\*.txt') do (
        set filename=%%i
        set filedt=!filename:~7%,-4!
        if %currdt% gtr !filedt! (move "C:\XXX\%%i" "C:\YYY\%%i")
    )
    pause
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-27
      • 2012-03-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多