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

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

问题描述

在 DOS 批处理文件中,实现某些事情的方法有些模糊.幸运的是,有一个很棒的批处理脚本参考站点:Simon Sheppard 的 SS64.(同一个站点也有大量关于 Bash 的信息.)

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

一个困难是根据目录是否为空来分支执行.明显的 if exists "%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
)

所以,我的问题是:
有没有办法根据文件的时间戳做分支?

这就是我想要的东西:

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

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

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