15

I'd like to merge two files by doing the following:

  1. Output the diff of the two files into a temp file and
  2. Manually select the lines I want to copy/save.

The problem here is that diff -u only gives me a file lines of context, while I want to output the entire file in a unified format.

Is there any way diff can do this?

2
  • 1
    I know a lot of people like using vim in diff mode to do this, and there are a few plugins that make three buffer (old, merge, 'new') work better.
    – demure
    Jun 3, 2013 at 17:06
  • What's the problem? Just delete the parts of the patch that you don't want to have and then patch the file. Also note about git cherry picking. This is exactly what you want to do
    – hek2mgl
    Jun 3, 2013 at 17:06

5 Answers 5

20

One option that might fit the bill for you,

sdiff : side-by-side diff of files.

sdiff -o merged.file left.file right.file

Once there, it will prompt you with what lines you want to keep from which file. Hit ? and then enter for a little help. Also man sdiff with the detailed goods.

(In my distro, these come packaged in the "diffutils" package [fedora,centos])

If you need to automate the process, you might want to try the util merge, which will mark conflicts in the files. However, that might put you back at square one.

11

"I want to output the entire file in a unified format. Is there any way diff can do this?"

Yes.

diff -U 9999999 file1.txt file2.txt > diff.txt

This should work, provided your files are less than 10 million lines long.

2
  • 1
    This adds + and - signs in front of diffing lines in merged file
    – Davi Lima
    Feb 16, 2019 at 8:09
  • 1
    It is not a merged file, it is in unified diff format, as the OP requested, so the + and - are expected.
    – dcorking
    Apr 5, 2020 at 14:03
10

You can merge/combine the two files with diff using --

diff --line-format %L file1 file2
0
0

The easy answer is to use the -D flag to merge the files and surround the differences with C style #ifdef statements.

From the documentation:

-D NAME  --ifdef=NAME
          Output merged file to show `#ifdef NAME' diffs.

You can use it as follows:

$ diff -D NEWSTUFF file1 file2 > merged_file

I usually then just open the merged file in an editor and resolve the merge conflicts by hand.

You also can use options to output an ed script, etc.

0

If you are an emacs user, you can do this directly in emacs using the "emerge" tool:

https://www.gnu.org/software/emacs/manual/html_node/emacs/Emerge.html

Issuing M-x emerge-files will open an interactive prompt with a view of files A, B, and the merged file to allow choosing text that differs between files A & B, inserting part of A into B, and more.

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.