How do I merge changes to a single file, rather than merging commits? How do I merge changes to a single file, rather than merging commits? git git

How do I merge changes to a single file, rather than merging commits?


I came across the same problem. To be precise, I have two branches A and B with the same files but a different programming interface in some files. Now the methods of file f, which is independent of the interface differences in the two branches, were changed in branch B, but the change is important for both branches. Thus, I need to merge just file f of branch B into file f of branch A.

A simple command already solved the problem for me if I assume that all changes are committed in both branches A and B:

git checkout Agit checkout --patch B f

The first command switches into branch A, into where I want to merge B's version of the file f. The second command patches the file f with f of HEAD of B. You may even accept/discard single parts of the patch. Instead of B you can specify any commit here, it does not have to be HEAD.

Community edit: If the file f on B does not exist on A yet, then omit the --patch option. Otherwise, you'll get a "No Change." message.


This uses git's internal difftool.Maybe a little work to do but straight forward.

#First checkout the branch you want to merge intogit checkout <branch_to_merge_into>    #Then checkout the file from the branch you want to merge fromgit checkout <branch_to_merge_from> -- <file>     #Then you have to unstage that file to be able to use difftoolgit reset HEAD <file> #Now use difftool to chose which lines to keep. Click on the mergebutton in difftoolgit difftool#Save the file in difftool and you should be done.


Here's what I do in these situations. It's a kludge but it works just fine for me.

  1. Create another branch based off of your working branch.
  2. git pull/git merge the revision (SHA1) which contains the file you want to copy. So this will merge all of your changes, but we are only using this branch to grab the one file.
  3. Fix up any Conflicts etc. investigate your file.
  4. checkout your working branch
  5. Checkout the file commited from your merge.
  6. Commit it.

I tried patching and my situation was too ugly for it. So in short it would look like this:

Working Branch: A Experimental Branch: B (contains file.txt which has changes I want to fold in.)

git checkout A

Create new branch based on A:

git checkout -b tempAB

Merge B into tempAB

git merge B

Copy the sha1 hash of the merge:

git logcommit 8dad944210dfb901695975886737dc35614fa94eMerge: ea3aec1 0f76e61Author: matthewe <matthewe@matthewe.com>Date:   Wed Oct 3 15:13:24 2012 -0700Merge branch 'B' into tempAB

Checkout your working branch:

git checkout A

Checkout your fixed-up file:

git checkout 7e65b5a52e5f8b1979d75dffbbe4f7ee7dad5017 file.txt

And there you should have it. Commit your result.