Looking for a remote web / back-end engineer?
You should check out my resume (PDF) and give me a call.

How to Merge Specific Files From Another Branch in Git

There are many ways to get specific files from another git branch into your current git branch (overwriting the ones in your current branch), but this is the only method I’ve been able to find to merge those files into your branch en-masse. With this method you’ll be able to pull in any file, or files based on the name of the file or containing folder. If you need to merge files in multiple folders on different subdirectories you can simply rerun step two with a pattern that matches each of the different portions of your tree that you wish to merge.

Please note that this was originally an answer on Stack Overflow, but I felt it could do with a reposting since it’s a commonly asked question and there are lots of poor answers out there that don’t really answer it.

So, without further ado, the simple way, to actually merge specific files from two branches, not just replace specific files with ones from another branch:

Step one: Diff the branches

git diff branch_b > my_patch_file.patch

Creates a patch file of the difference between the current branch and branch_b

Step two: Apply the patch on files matching a pattern

git apply -p1 --include=pattern/matching/the/path/to/file/or/folder

useful notes on the options

You can use * as a wildcard in the include pattern.

Slashes don’t need to be escaped.

Also, you could use –exclude instead and apply it to everything except the files matching the pattern, or reverse the patch with -R

The -p1 option is a holdover from the *unix patch command and the fact that the patch file’s contents prepend each file name with a/ or b/ ( or more depending on how the patch file was generated) which you need to strip so that it can figure out the real file to the path to the file the patch needs to be applied to.

Check out the man page for git-apply for more options.

Step three: there is no step three

Obviously you’d want to commit your changes, but who’s to say you don’t have some other related tweaks you want to do before making your commit.


If you found this useful you might be interested in some of the other git posts here.