((gnu)diff-显示相应的行号

问题描述 投票:0回答:1

我正在尝试为我的文本编辑器(Kakoune)构建差异查看器插件。我正在比较两个文件,并标记两个窗格之间不同的任何行。

但是,两个视图不会同时滚动。我的想法是获取相互对应的行号列表,以便在切换窗格时可以正确放置光标,或者在主窗口滚动时滚动辅助窗口,等等。

所以-有没有办法从命令行diff获取相应编号的列表?

我希望通过以下示例进行操作:给定文件A和B,输出应告诉我(未更改的行号)对应的行号。

File A         File B            Output          
1: hello       1: hello          1:1
2: world       2: another        2:3
3: this        3: world          3:4
4: is          4: this           4:5
5: a           5: is
6: test        6: eof

目标是,当我滚动到文件A中的第4行时,我将知道滚动文件B以便将其第5行呈现在同一位置。

不必一定是Gnu diff,而应该只使用大多数/所有Linux机器上都可用的工具。

unix command-line-interface diff
1个回答
1
投票

我可以使用GNU diff获得某些方法,但是需要一个python脚本对其进行后处理,以将基于组的输出转换为基于行的输出。

#!/usr/bin/env python

import sys
import subprocess

file1, file2 = sys.argv[1:]

cmd = ["diff",
       "--changed-group-format=",
       "--unchanged-group-format=%df %dl %dF %dL,",
       file1,
       file2]

p = subprocess.Popen(cmd, stdout=subprocess.PIPE)
output = p.communicate()[0]

for item in output.split(",")[:-1]:
    start1, end1, start2, end2 = [int(s) for s in item.split()]
    n = end1 - start1 + 1
    assert(n == end2 - start2 + 1)  # unchanged group, should be same length in each file
    for i in range(n):
        print("{}:{}".format(start1 + i, start2 + i))

给予:

$ ./compare.py fileA fileB
1:1
2:3
3:4
4:5
© www.soinside.com 2019 - 2024. All rights reserved.