【问题标题】:find oldest file from list从列表中查找最旧的文件
【发布时间】:2014-05-28 04:18:42
【问题描述】:

我有一个文件,其中包含不同目录中的文件列表,并且想要找到最旧的文件。 感觉就像使用一些 shell 脚本应该很容易,但我不知道如何解决这个问题。我确信在 perl 和其他脚本语言中这真的很容易,但我真的很想知道我是否错过了一些明显的 bash 解决方案。

源文件内容示例:

/home/user2/file1  
/home/user14/tmp/file3  
/home/user9/documents/file9

【问题讨论】:

  • 我建议将find(用于列出文件)、ls -lc(用于排序和显示)和xargs结合起来。
  • 喜欢这个find . -type f -printf '%T+ %p\n' | sort | head -1 ?
  • 如何将查找命令限制为列表中已有的文件?

标签: bash sorting


【解决方案1】:
#!/bin/sh

while IFS= read -r file; do
    [ "${file}" -ot "${oldest=$file}" ] && oldest=${file}
done < filelist.txt

echo "the oldest file is '${oldest}'"

【讨论】:

    【解决方案2】:

    您可以使用stat 查找每个文件的最后修改时间,循环访问您的源文件:

    oldest=5555555555
    while read file; do
        modtime=$(stat -c %Y "$file")
        [[ $modtime -lt $oldest ]] && oldest=$modtime && oldestf="$file"
    done < sourcefile.txt
    echo "Oldest file: $oldestf"
    

    这使用stat%Y格式,这是最后一次修改时间。您也可以使用%X 作为上次访问时间,或使用%Z 作为上次更改时间。

    【讨论】:

    • 遗憾的是,stat 是高度不可移植的,所以这基本上只适用于 Linux。
    【解决方案3】:

    使用find() 查找最旧的文件:

    find /home/ -type f -printf '%T+ %p\n' | sort | head -1 | cut -d' ' -f2-
    

    还有源文件:

    find $(cat /path/to/source/file) -type f -printf '%T+ %p\n' | sort | head -1 | cut -d' ' -f2-
    

    【讨论】:

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