如何突出显示文件中后续行之间的差异?

时间:2010-10-01 11:32:06

标签: linux logging formatting diff

我对大型日志文件分析做了很多紧急分析。通常这需要拖尾日志并寻找变化。

我渴望有一个能突出这些变化的解决方案,让眼睛更容易追踪。

我已经调查了工具,似乎没有任何东西能够满足我的需求。我在Perl中编写了一些大致完成的脚本,但我想要一个更完整的解决方案。

有人可以为此推荐一个工具吗?

3 个答案:

答案 0 :(得分:3)

Levenshtein距离

百科: 两个字符串之间的Levenshtein距离是将一个字符串转换为另一个字符串所需的最小操作数,其中操作是单个字符的插入,删除或替换。

public static int LevenshteinDistance(char[] s1, char[] s2) {
    int s1p = s1.length, s2p = s2.length;
    int[][] num = new int[s1p + 1][s2p + 1];

    // fill arrays
    for (int i = 0; i <= s1p; i++)
        num[i][0] = i;

    for (int i = 0; i <= s2p; i++)
        num[0][i] = i;

    for (int i = 1; i <= s1p; i++)
        for (int j = 1; j <= s2p; j++)
            num[i][j] = Math.min(Math.min(num[i - 1][j] + 1,
                    num[i][j - 1] + 1), num[i - 1][j - 1]
                    + (s1[i - 1] == s2[j - 1] ? 0 : 1));

    return num[s1p][s2p];
}

Java中的示例应用程序

String Diff

alt text

应用程序使用LCS算法将2个文本输入连接成1.结果将包含最少的指令集,以便为另一个生成一个字符串。在指令下方显示连接文本。

下载应用程序:     String Diff.jar

下载源代码:     Diff.java

答案 1 :(得分:1)

我为此目的编写了一个Python脚本,它使用了difflib.SequenceMatcher

#!/usr/bin/python3

from difflib import SequenceMatcher
from itertools import tee
from sys import stdin

def pairwise(iterable):
    """s -> (s0,s1), (s1,s2), (s2, s3), ...

    https://docs.python.org/3/library/itertools.html#itertools-recipes
    """
    a, b = tee(iterable)
    next(b, None)
    return zip(a, b)

def color(c, s):
  """Wrap string s in color c.

  Based on http://stackoverflow.com/a/287944/1916449
  """
  try:
    lookup = {'r':'\033[91m', 'g':'\033[92m', 'b':'\033[1m'}
    return lookup[c] + str(s) + '\033[0m'
  except KeyError:
    return s

def diff(a, b):
  """Returns a list of paired and colored differences between a and b."""
  for tag, i, j, k, l in SequenceMatcher(None, a, b).get_opcodes():
    if tag == 'equal': yield 2 * [color('w', a[i:j])]
    if tag in ('delete', 'replace'): yield color('r', a[i:j]), ''
    if tag in ('insert', 'replace'): yield '', color('g', b[k:l])

if __name__ == '__main__':
  for a, b in pairwise(stdin):
    print(*map(''.join, zip(*diff(a, b))), sep='')

示例input.txt

108  finished   /tmp/ts-out.5KS8bq   0       435.63/429.00/6.29 ./eval.exe -z 30
107  finished   /tmp/ts-out.z0tKmX   0       456.10/448.36/7.26 ./eval.exe -z 30
110  finished   /tmp/ts-out.wrYCrk   0       0.00/0.00/0.00 tail -n 1
111  finished   /tmp/ts-out.HALY18   0       460.65/456.02/4.47 ./eval.exe -z 30
112  finished   /tmp/ts-out.6hdkH5   0       292.26/272.98/19.12 ./eval.exe -z 1000
113  finished   /tmp/ts-out.eFBgoG   0       837.49/825.82/11.34 ./eval.exe -z 10

cat input.txt | ./linediff.py的输出:

linediff output

答案 2 :(得分:0)

http://neil.fraser.name/software/diff_match_patch/svn/trunk/demos/demo_diff.html

..这看起来很有希望,当我玩更多的时候会更多信息更新这个...