Diff + patch - Sum instead of replace

做~自己de王妃 提交于 2019-12-11 05:09:27

问题


Say I have a file A, which contains this:

a = 5

And a file B, like this:

b = 5

Now, it's obvious that diff will produce something like this (the patch):

1c1

< a = 5

---

> b = 5

Patching file A will obviously replace its contents with those of file B, resulting in file A containing

b = 5

What I want to do, however, is different. I want the contents of files A and B to merge, so that after patching file A it will contain

a = 5

b = 5

My case if course way more complex than my example but I think I've figured it out except for the summative diff/patch at the end.

tl;dr: I want the diff/patch to sum rather than replace the differences in the files. How can I do that?


回答1:


You don't want to patch some files, you are trying to merge them. There are lot's of tools out there that will help you, e.g. take a look at kdiff!

Edit: Some more tools:

  • meld
  • gPyFm
  • diff3
  • tkdiff
  • P4Merge

At least vim -d will do the job ;-)




回答2:


You tell very very little about what problem you are trying to solve (or you talk too much about how the approach you took did not work). What's more interesting is what you want done.

Perhaps you could be done with

sort -u A B

Because it will give the output you require with the inputs you provide.




回答3:


The diff command from the GNU diffutils packages provides an option to merge two different files by inserting #ifdef preprocessor instructions. For instance consider 2 files f1 and f2 (displayed side-by-side):

line 1     |   line 1
line 2     |   line 2
line 3a    |   line 3a
line 4     |   line 4
line 5a    |   line 5a

Calling diff -D MARKER f1 f2 will produce this merged output:

line 1
line 2
#ifndef MARKER
line 3a
#else /* MARKER */
line 3b
#endif /* MARKER */
line 4
#ifndef MARKER
line 5a
#else /* MARKER */
line 5c
#endif /* MARKER */

You can strip the preprocessor instructions to get a clean merged file, e.g. by using grep:

diff -D MARKER f1 f2 | grep -v "MARKER"

Note that the token MARKER must not exist in the original input files, so you should better use something more special, e.g. a random token like c11ced4751ef4b3aa60e512bdaa184210441b4ed0.



来源:https://stackoverflow.com/questions/6405254/diff-patch-sum-instead-of-replace

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!