对多个文件使用 diff 进行成对比较。如果有相同的 - 只显示它们。如果 none 个相同 - 显示消息

Pairwise comparison using diff on multiple files. If there are same - display only them. If none of them are same - display message

我想在 bash.

中使用 diff 成对比较小的多个文件(超过 70 个)

如果找到相同的文件 - 只应显示它们:

>Files t01 and t03 are the same
>Files t10 and t15 are the same

如果所有文件都是唯一的 - 应显示一条消息:

>All files are unique

下面的代码片段对所有匹配的文件运行一个循环,然后检查 diff 的 return 值,如果值为 0,它会打印文件相似的消息:

FILES=./dir/t*
for data1 in $FILES; do
    for data2 in $FILES; do
        if [[ "$data1" != "$data2" ]]
        then

            diff $data1 $data2 > /dev/null
            if [[ $? -eq 0 ]]
             then
                echo "The files $(basename ${data1}) and $(basename ${data2}) are same."
            
             fi
        fi

    done
done    

如果我从文件夹中删除类似的文件,则不会显示任何内容。

如果我将 else 添加到 if [[ $? -eq 0 ]] 语句,如果存在类似文件,输出将如下所示:

    >Files t01 and t03 are the same
    >All files are unique
    >All files are unique
    >Files t10 and t15 are the same
    >All files are unique
    >All files are unique
    ...

不幸的是,我不知道如何继续代码以使其正常工作。如果有人能提供帮助,我将不胜感激。

首先展开数组中的 glob:

files=( ./dir/t* )

然后使用嵌套的for循环生成对并在内部进行比较;添加一个变量用于记忆是否命中:

found=false

for ((i = 0; i < ${#files[@]} ; i++))
do
    for ((j = i+1; j < ${#files[@]}; j++))
    do
        if diff -q "${files[i]}" "${files[j]}" > /dev/null
        then
            found=true
            echo "Files ${files[i]##*/} and ${files[j]##*/} are identical"
        fi
    done
done

! "$found" && echo "Files are unique"