Question

When I add a line to the middle of a file, all following lines have their number incremented.

Is there a utility that generates the list of equivalent line numbers between two files?

The output would be something like:

1 1
2 2
3 4 (line added)
4 5

One can probably create such utility by using dynamic programming in a way similar to the diff algorithm. Seems useful, hasn't already been done?

Was it helpful?

Solution

I found out it is pretty easy to do with python's difflib:

import difflib

def seq_equivs(s1, s2):
    equiv = []
    s = difflib.SequenceMatcher(a=s1, b=s2)
    for m in s.get_matching_blocks():
        if m[2] == 0:
            break
        for n in range(1, 1+m[2]):
            equiv.append((m[0]+n, m[1]+n))
    return equiv

Example usage:

f1 = open('file1.txt').read().split('\n')
f2 = open('file2.txt').read().split('\n')

for equivs in seq_equivs(f1, f2):
    print('%d %d' % equivs)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top