【问题标题】:How to compare if the two newest files in a directory are identical using a shell script? [duplicate]如何使用 shell 脚本比较目录中的两个最新文件是否相同? [复制]
【发布时间】:2016-03-02 08:51:30
【问题描述】:

我正在寻找一种简单的方法来获得 if 语句,其中条件是给定目录中的 2 个最新文件(递归地)内容是否相同。

【问题讨论】:

  • 这真的是两个问题合二为一:(1)获取目录中两个最新文件的名称(递归与否?不清楚); (2) 比较给定路径的两个文件。 (2) 非常简单(diffcmp 等)。 (1)据我所知并不是那么容易。有ls -t,但解析ls 输出总是不受欢迎;然后是stat,但您可能需要手动对时间戳进行排序。
  • 是的,是2题合一。这就是为什么它不是链接到问题的副本。我可以在评论中给出答案,但我认为值得重新提出这个问题。毕竟,我来到这里是因为我有完全相同的问题。
  • 简短的回答是:readarray -t files < <(ls -t /your/dir/ | head -2); if diff -q "${files[@]}"; then echo identical; fi。如果您确定文件名永远不能包含空格,则可以使用更简单的files=$(ls -t /your/dir/ | head -2); if diff -q $files; then echo identical; fi。但是总有一天,文件名中会有空格……

标签: bash shell timestamp file-comparison


【解决方案1】:

在不解析 ls 的情况下比较 bash 目录中包含的文件的一种方法是:

unset -v penultimate  ## one before newest
unset -v latest       ## newest

for file in "$dirname"/*; do
    [[ $file -nt $latest ]] && penultimate="$latest" && latest="$file"
done

if [[ -f $latest ]] && [[ -f $penultimate ]]; then
    if diff -q "$penultimate" "$latest" ; then
        printf "Files '%s' and '%s' are identical\n" "$penultimate" "$latest"
    fi
fi

注意:如果文件不同,diff -q 的默认行为将输出:Files '%s' and '%s' differ\n" "$penultimate" "$latest"。另请注意,上面比较了 2 个文件的存在,而不是最新的两个文件中的任何一个是否是符号链接。它进一步不比较给定目录的子目录的内容。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多