如何使用“diff”或其他命令获得差异比?

如何使用“diff”或其他命令获得差异比?

我有两个包含数千行的文件。我想使用以下方法获得它们的行/字节差异比差异,维姆迪夫或其他命令,即使不考虑具体差异。

答案1

有一个名为 的工具diffstat听起来像是您正在寻找的工具。

$ diff <file1> <file2> | diffstat

例子

$ diff afpuri.c afpuri1.c | diffstat
 unknown |   53 ++++++++++++++++++++---------------------------------
 1 file changed, 20 insertions(+), 33 deletions(-)

diff这也可用于在树中包含多个文件的输出。

参考

答案2

我的数学可能有点偏差,但我相信你要求一个比率,并且我相信这会产生一个比率。

#!/usr/bin/env bash

# File 1 contains 1,2,3,4,5 on new lines
# File 2 contains 1,2,3,4,5,6,7,8,9,10 on new lines.

# Compare differentials side-by-side
diff -y 1 2 > diff

# Print lines to file which do not contain ">" prefix.
sed 's/[ ]/d' diff > MATCHES

# Print lines to file which do contain ">" prefix.
sed '/[>]/!d' diff > DIFFS

# Count lines in file that contains MATCHES between Versions of Files 1,2.
MATCHES=$(wc -l MATCHES | sed 's/[^0-9]*//g')

# Count lines in file that DID NOT MATCH between Version of Files 1,2.
DIFFS=$(wc -l DIFFS | sed 's/[^0-9]*//g')

# Sed here is stripping all but the number of lines in file.

RATIO=$(echo "$MATCHES / $DIFFS" | bc -l)

# To get the ratio, we are echoing the #of_matches and the #of_diffs to
# the bc -l command which will give us a float, if we need it.
echo "You've got:" $RATIO "differential."

# Bytes...
# stat -c%s prints bytes to variable
MATCHES=$(stat -c%s MATCHES)
DIFFS=$(stat -c%s DIFFS)

RATIO_BYTE=$(echo "$MATCHES / $DIFFS" | bc -l)
echo "Let Ratio in Bytes be" $RATIO_BYTE
# Again, we divide the matches by the diffs to reach the "ratio" of
# differences between the files.

相关内容