1

I have a seemingly simple question I can't find answer for.

Say, I have two files:

A
B
C
D

and

A
X
Y
D

When I run diff -U 1000 on these, I get:

 A
-B
-C
+X
+Y
 D

Instead, I'd like to get:

 A
-B
+X
-C
+Y
 D

Big picture to understand what I'm trying to accomplish: I have a scheduled script that runs smartctl on my hard drives, keep the historic data, and compare them. So, the changed lines are, indeed, individual replacements for the corresponding lines of the earlier file:

-  3 Spin_Up_Time      0x0027   173   168   021    Pre-fail  Always    -    2350
-  4 Start_Stop_Count  0x0032   096   096   000    Old_age   Always    -    4445
+  3 Spin_Up_Time      0x0027   172   168   021    Pre-fail  Always    -    2358
+  4 Start_Stop_Count  0x0032   096   096   000    Old_age   Always    -    4461
0

I've ended up with a two-step process: passing to to git diff and then post-processing it with an AWK script:

     git diff --word-diff=porcelain -U10000 %1 %2  |
     awk -f mysmartdiff.awk;

The first step returns a result in the following form:

~
   3 Spin_Up_Time            0x0027
-172
+173
    168   021    Pre-fail  Always       -
-2358
+2333

and the second script does this:

screenshot of final result

The mysmartdiff.awk script is the following:

BEGIN {
    DEBUG=0
    l1=""
    l2=""
    old=""
    new=""
}
function dprint(s) { if(DEBUG) {print s > "/dev/stderr"} }

function appendDiff() {
    if(length(old)!=0 || length(new)!=0) {
        l1 = l1"\033[1;31m"old"\033[0m"
        l2 = l2"\033[1;32m"new"\033[0m"
        old="";new="";
    }
}
{
    dprint(">>>>>>>>>>>>>>")
    dprint("ORIG: " $0)
    if(match($0, /^ /)) {
        appendDiff();
        l1 = l1""substr($0,2)
        l2 = l2""gensub(/[^-]/, " ", "g", substr($0,2)); ## leave '-' to aid further space trimming
    } else if(match($0, /^~/)) {
        appendDiff();
        print l1;
        if(l2 !~ /^[ -]+$/) {
            print l2;
        }
        l1=""
        l2=""
    } else if(match($0, /^-/)) {
        old=substr($0,2);
    } else if(match($0, /^+/)) {
        new=substr($0,2);
    }
}
| improve this answer | |

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.