【问题标题】:Newest file in directories目录中的最新文件
【发布时间】:2013-12-04 00:48:45
【问题描述】:

您好,我有两个目录

目录 1:

song.mp3
work.txt

目录 2:

song.mp3
work.txt

这些文件是一样的,但是 directory1 中的 song.mp3 比 directory2 中的 song.mp3 新,并且目录 2 中的 work.txt 比目录 1 中的 work.txt 最新。

现在我如何打印两个文件,例如 在 file1 中的文件比目录 2 中的文件更新,所以它必须是 song.mp3 并且在 file2 文件中比目录 1 中的文件更新,所以它必须是 work.txt

我试过了

find $directory1 -type f -newer $directory2

但它总是向我打印两个目录中的最新文件。有人可以帮我吗?

【问题讨论】:

    标签: bash directory


    【解决方案1】:

    -newer $directory2 只是使用目录$directory2 上的时间戳作为所有比较的参考点。它不会查看$directory2 中的任何文件。

    我认为find 中没有内置的“将每个文件与另一个目录中的对应文件进行比较”之类的操作,因此您可能必须自己完成一些工作。这是一个简短的脚本,演示了一种可以完成的方法:

    (cd $directory1 && find . -print) | while IFS= read -r fn; do
      if [ "$directory1/$fn" -nt "$directory2/$fn" ]; then
        printf "%s\n" "$directory1/$fn"
      else
        printf "%s\n" "$directory2/$fn"
      fi
    done
    

    【讨论】:

      【解决方案2】:
      # set up the test
      mkdir directory1 directory2
      touch directory1/song.mp3
      touch -t 200101010000 directory1/work.txt
      touch -t 200101010000 directory2/work.txt
      touch directory2/work.txt
      
      # find the newest of each filename:
      #  sort the files in both directories by mtime
      #  then only output the filename (regardless of directory) the first time seen
      stat -c '%Y %n' directory[12]/* | 
      sort -rn | 
      cut -d " " -f 2- | 
      awk -F / '!seen[$2]++'
      
      directory2/work.txt
      directory1/song.mp3
      

      【讨论】:

        【解决方案3】:

        如果您使用的 Linux 支持以下功能:

        Fileage=`date +%s -r filename`
        

        您可以运行“查找”并以秒为单位打印年龄,后跟每个文件的文件名,然后对该文件进行排序。这样做的好处是它可以在任意数量的目录中工作——而不仅仅是两个。 Glenn 更广泛使用的“stat -c”可以用来代替我的“date”命令——他已经为你完成了“sort”和“awk”!

        【讨论】:

          猜你喜欢
          • 2016-04-05
          • 2011-12-08
          • 2012-03-11
          • 1970-01-01
          • 1970-01-01
          • 2021-01-12
          • 1970-01-01
          • 2021-10-30
          • 2014-09-19
          相关资源
          最近更新 更多