2

Suppose I have the following files:

file0.c:

int b=NULL;
int a=NULL;

file1.c:

int b;
int a=NULL;

file2.c:

int b;
int a=NULL;

I am looking to merge the files file1 and file2 to generate the following result.c:

int b;
int a;

I can use : diff input0 input1 and diff input0 input2 to get the line+column combinations, however I don't know what to do next in order to achieve the above results.

7
  • Is each number supposed to be a line? If so then writem them as lines. There are two differences, not just one. Maybe a typo. Commented Feb 23, 2014 at 18:54
  • I have made changes to make the problem more understandable, one solution could be to get the line number from diff and then replace using sed? Commented Feb 23, 2014 at 19:00
  • diff -D00-11 file0.c file1.c > merged.c and edit away the resulting #ifdef and unwanted lines. (assuming you are working with only small differences.)
    – D McKeon
    Commented Feb 23, 2014 at 19:19
  • 1
    Achieve what results? It looks like you want to delete all lines where a variable is set to something. Please edit your question and make your examples (and file names) consistent with what you want to do.
    – terdon
    Commented Feb 24, 2014 at 12:54
  • 1
    Why does the result file have "int a;" instead of "int a=NULL;"?
    – dannysauer
    Commented Feb 26, 2014 at 15:23

1 Answer 1

0

It seems like file2.c should be:

int b=NULL;
int a;

rather than a copy of file1.c.

With that change, what we can understand is that file0.c is a common ancestor (the "merge base") for file1.c and file2.c, which each fix half of the bug of using NULL to initialize int variables.

If the changes weren't so close together, we could use diff3 -m file1.c file0.c file2.c. Alas, that will just output a conflict marker.

However, if we know that what is going on is nothing but one-line substitutions—that is, no lines are being added, removed or or moved, only fixed in place—we can obtain the two deltas 0-1 and 0-2 as ed script diffs with diff -e. We can catenate these scripts and then use ed to apply them.

First, let's make a copy of file0.c called test.c. We will try to apply those changes to test.c:

$ cp file0.c test.c

Now, let's collect the ed style patches:

$ (diff -e file0.c file1.c ; diff -e file0.c file2.c) > patch

What do they look like?

$ cat patch
1c
int b;
.
2c
int a;
.

That looks an awful lot like the correct commands to turn test.c into the desired merged file. What's missing is the wq to save:

$ echo wq >> patch

Now let's try it:

$ cat test.c
int b=NULL;
int a=NULL;
$ ed test.c < patch
ed test.c < patch
24
14
$ cat test.c
int b;
int a;

Done.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .