Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have two branches (A and B) and I want to merge a single file from branch A with a corresponding single file from Branch B.

like image 372
Isuru Avatar asked May 28 '12 12:05

Isuru


People also ask

How do I merge individual files in git?

We can use git checkout for far more than simply changing branches. If we supply it with a branch name and a file, we can replace a corrupted or broken file. Instead, if we want to pass some of the changed content we can use the --patch flag to manually merge an individual file.


1 Answers

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 A  git 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.

like image 139
loup Avatar answered Oct 02 '22 09:10

loup