【问题标题】:Finding files by creation time of another file通过另一个文件的创建时间查找文件
【发布时间】:2021-06-26 16:17:49
【问题描述】:

我需要做的是通过另一个文件的创建时间来查找文件。例如,如果我在上午 9 点创建一个文件,然后我想查找在它之后 1 小时或在它之前 1 小时创建的所有文件。我该怎么做?

我在使用“find”的同时尝试使用“-newer”,但我认为“xargs”是我需要使用的。

谢谢

【问题讨论】:

  • 在 linux 上不存储文件创建时间,只存储访问、修改和更改时间 (unix.stackexchange.com/questions/24441/…)。如果您将“创建时间”替换为“修改时间”,您的要求是否仍然有效?
  • 是的,可以接受。

标签: linux bash find xargs


【解决方案1】:

我知道这太旧了,但因为我一直在寻找同样的东西...... 这是一个oneliner版本,基本上使用与上面相同的方法:

至少一小时后修改:

find . -newermt "$(date -d "$(stat -c %y reference_file) + 1 hour")"

提前一小时或更长时间修改:

find . -not -newermt "$(date -d "$(stat -c %y reference_file) - 1 hour")"

在从前一小时到一小时后的时间跨度内修改

find . -newermt "$(date -d "$(stat -c %y reference_file) - 1 hour")" -not -newermt "$(date -d "$(stat -c %y reference_file) + 1 hour")"

reference_file 替换为您选择的文件。当然你也可以使用1 hour以外的其他时间跨度

工作原理

stat -c %y reference_file会返回修改时间。

date -d "[...] + 1 hour" 会将日期字符串修改为一小时后。

find . -newermt "[...]" 将查找修改时间 (m) 比给定时间 (t) 新的文件

所有这些都需要 GNU find 4.3.3 或更高版本(用于 -newerXY)和 GNU date(以支持 -d 和复杂的日期字符串)

【讨论】:

    【解决方案2】:

    看了这个之后,我找到了一种方法,虽然它不是最好的解决方案,因为它需要按时完成整数运算。

    这个想法是从您的参考文件中获取自 Unix 纪元(又名 Unix 时间)以来的秒数,对此进行一些整数运算以获得您的偏移时间(在您的示例中是一小时之前或之后)。然后你使用带有-newer 参数的find。

    示例代码:

    # Get the mtime of your reference file in unix time format, 
    # assumes 'reference_file' is the name of the file you're using as a benchmark
    reference_unix_time=$(ls -l --time-style=+%s reference_file | awk '{ print $6 }')
    
    # Offset 1 hour after reference time
    let unix_time_after="$reference_unix_time+60*60"
    
    # Convert to date time with GNU date, for future use with find command
    date_time=$(date --date @$unix_time_after '+%Y/%m/%d %H:%M:%S')
    
    # Find files (in current directory or below)which are newer than the reference 
    # time + 1hour
    find . -type f -newermt "$date_time"
    

    对于您在参考文件前一小时创建的文件示例,您可以使用

    # Offset 1 hour before reference time
    let unix_time_before="$reference_unix_time-60*60"
    
    # Convert to date time with GNU date...
    date_time=$(date --date @$unix_time_before '+%Y/%m/%d %H:%M:%S')
    
    # Find files (in current directory or below which were generated 
    # upto 1 hour before the reference file
    find . -type f -not -newermt "$date_time"
    

    请注意,以上都是基于文件的最后修改时间。

    以上内容已使用 GNU Find (4.5.10)、GNU Date (8.15) 和 GNU Bash (4.2.37) 进行了测试。

    【讨论】:

      猜你喜欢
      • 2014-08-23
      • 2015-01-19
      • 1970-01-01
      • 1970-01-01
      • 2015-01-14
      • 1970-01-01
      • 2013-02-10
      • 1970-01-01
      相关资源
      最近更新 更多