如何比较文件的时间戳在DOS批处理脚本? [英] How do I compare timestamps of files in a DOS batch script?

查看:182
本文介绍了如何比较文件的时间戳在DOS批处理脚本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在DOS批处理文件,实现某些事情的方法有所混淆。幸运的是,有一个DOS批处理脚本一个梦幻般的参考网站:西蒙Sheppard的SS64 。 (该站点上也有大量的信息有关的的。)

In DOS batch files, the method of achieving certain things is somewhat obfuscated. Fortunately, there is a fantastic reference site for DOS batch scripting: Simon Sheppard's SS64. (The same site also has plenty of information about Bash.)

的一个困难是基于一个目录是否为空的分支执行。
最明显的是否存在%DIR%\\ *。*不起作用。但它可以用这个条件执行招来完成:

One difficulty is branching execution based on whether a directory is empty. The obvious if exist "%dir%\*.*" doesn't work. But it can be done with this conditional execution trick:

( dir /b /a "%dir%" | findstr . ) > nul && (
  echo %dir% non-empty
) || (
  echo %dir% empty
)

另一个尴尬问题根据文件内容的分支。
同样可以这样做:

Another awkward problem is branching according to file contents. Again that can be done like this:

( fc /B "%file1%" "%file2%" | find "FC: no differences encountered" ) > nul && (
  echo "%file1%" and "%file2%" are the same
) || (
  echo "%file1%" and "%file2%" are different
)

所以,我的问题是:结果
有没有一种方法,根据文件的时间戳做分支?

这是诸如此类的事情,我想:

This is the sort of thing I want:

REM *** pseudo-code!
if "%file1%" is_newer_than "%file2%" (
  echo "%file1%" is newer
) else if "%file1%" is_older_than "%file2%" (
  echo "%file2%" is newer
) else (
  echo "%file1%" and "%file2%" are the same age
)

感谢。

推荐答案

您可以找到两个文件批处理脚本的一行的更新。只是列出文件按日期顺序排列,最古老的第一,这意味着上市必须在新文件中的最后一个文件。所以,如果你每次都保存的文件名,把你的变量姓氏将是最新的文件。

You can find the newer of two files with one line of batch script. Just list the files in date order, oldest first, which means the last file listed must be the newer file. So if you save the file name each time, the last name put in your variable will be the newest file.

有关,例如:

SET FILE1=foo.txt
SET FILE2=bar.txt
FOR /F %%i IN ('DIR /B /O:D %FILE1% %FILE2%') DO SET NEWEST=%%i
ECHO %NEWEST% is (probably) newer.

此遗憾的是不与日期戳是相同的对应。所以,我们只需要检查该文件具有相同的日期和时间标记第一:

This unfortunately doesn't cope with the date stamps being the same. So we just need to check if the files have the same date and time stamp first:

SET FILE1=foo.txt
SET FILE2=bar.txt

FOR %%i IN (%FILE1%) DO SET DATE1=%%~ti
FOR %%i IN (%FILE2%) DO SET DATE2=%%~ti
IF "%DATE1%"=="%DATE2%" ECHO Files have same age && GOTO END

FOR /F %%i IN ('DIR /B /O:D %FILE1% %FILE2%') DO SET NEWEST=%%i
ECHO Newer file is %NEWEST%

:END

这篇关于如何比较文件的时间戳在DOS批处理脚本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆