【问题标题】:Percentage value with GNU DiffGNU Diff 的百分比值
【发布时间】:2010-04-27 16:19:18
【问题描述】:

使用 diff 显示两个文件之间百分比差异的好方法是什么?

例如,如果一个文件有 100 行,而一个副本有 15 行已更改,则差异百分比将为 15%。

【问题讨论】:

  • 您可以使用 sdiff 计算分隔符,然后除以行数。
  • 差异文件 A 文件 B | wc -l 除以 wc -l fileA //似乎是一种有趣的手动方式。
  • 但问题是,当存在差异时,您会得到 3 行——原始、新和描述。所以你可能会高估。

标签: linux unix diff


【解决方案1】:

大概是这样的吧?

两个文件,A1 和 A2。

$ sdiff -B -b -s A1 A2 | wc 会告诉你有多少行不同。 wc 给出总数,除以。

-b 和 -B 是忽略空格和空行,-s 表示抑制公共行。

【讨论】:

  • 来自 wc 的 man 文件:换行符、单词和字节。您将输出中的第一个数字除以要比较的文件中的行数。 wc -l,只给你行数,可以添加到上面的命令中。 -- 对鳄鱼杰克的回应
  • @cdated :感谢您的澄清。在您发表评论之前,我当然没有看到问题/回复。
【解决方案2】:

https://superuser.com/questions/347560/is-there-a-tool-to-measure-file-difference-percentage 对此有一个巧妙的解决方案,

wdiff -s file1.txt file2.txt

更多选项见man wdiff

【讨论】:

  • 我猜这仅适用于文本,而不是像视频这样的媒体,我不断获得近乎重复的内容(由于 youtube-dl 的变化)。
【解决方案3】:

这是一个脚本,它将比较所有 .txt 文件并显示重复率超过 15% 的文件:

#!/bin/bash

# walk through all files in the current dir (and subdirs)
# and compare them with other files, showing percentage
# of duplication.

# which type files to compare?
# (wouldn't make sense to compare binary formats)
ext="txt"

# support filenames with spaces:
IFS=$(echo -en "\n\b")

working_dir="$PWD"
working_dir_name=$(echo $working_dir | sed 's|.*/||')
all_files="$working_dir/../$working_dir_name-filelist.txt"
remaining_files="$working_dir/../$working_dir_name-remaining.txt"

# get information about files:
find -type f -print0 | xargs -0 stat -c "%s %n" | grep -v "/\." | \
     grep "\.$ext" | sort -nr > $all_files

cp $all_files $remaining_files

while read string; do
    fileA=$(echo $string | sed 's/.[^.]*\./\./')
    tail -n +2 "$remaining_files" > $remaining_files.temp
    mv $remaining_files.temp $remaining_files
    # remove empty lines since they produce false positives
    sed '/^$/d' $fileA > tempA

    echo Comparing $fileA with other files...

    while read string; do
        fileB=$(echo $string | sed 's/.[^.]*\./\./')
        sed '/^$/d' $fileB > tempB
        A_len=$(cat tempA | wc -l)
        B_len=$(cat tempB | wc -l)

        differences=$(sdiff -B -s tempA tempB | wc -l)
        common=$(expr $A_len - $differences)

        percentage=$(echo "100 * $common / $B_len" | bc)
        if [[ $percentage -gt 15 ]]; then
            echo "  $percentage% duplication in" \
                 "$(echo $fileB | sed 's|\./||')"
        fi
    done < "$remaining_files"
    echo " "
done < "$all_files"

rm tempA
rm tempB
rm $all_files
rm $remaining_files

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-10-11
    • 2012-11-26
    • 1970-01-01
    • 2019-06-08
    • 2019-09-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多