1

I tried using this command to compute number of lines changed between two files:

diff -U 0 file1 file2 | grep ^@ | wc -l

My problem with this command is that if one file has only one line, and the other file has 100 lines, the output is still just 1.

What command would give me the total number of lines changed, including the total extra lines in one file?

4

Looking for lines starting with @ gives you the number of blocks of changes that diff found. They would often be more than one line.

As it happens, there's a tool to count the statistics of a diff: diffstat (web site, man page).

Count insertions and deletions:

$ diff -u test1 test2 | diffstat
 test2 |    3 +--
 1 file changed, 1 insertion(+), 2 deletions(-)

Combine insertions and deletions in the same block to just single "modification" operations:

$ diff -u test1 test2 | diffstat -m
 test2 |    2 -!
 1 file changed, 1 deletion(-), 1 modification(!)

Also, you could use diffstat -t to get a tabular output of just the numbers of modified lines.

The test files:

$ cat test1
a
b
c
d
$ cat test2
a
x
d
-1
Cat <file1> <file2> | sort | uniq | wc -l

This works for me

  • 2
    That counts the number of unique lines in both files taken together; if you use that as the number of changed lines you’re in for some surprises! – Stephen Kitt Jan 10 '18 at 16:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.