How to apply a Git patch to a file with a different name and path?

There is a simple solution that does not involve manual patch editing nor external script.

In the first repository (this may also export a range of commit, add the -1 flag if you want to select only one commit) :

git format-patch --relative <committish> --stdout > ~/patch

In the second repository :

git am --directory blue/red/ ~/patch

Instead of using --relative in git format-patch, another solution is to use -p<n> option in git am to strip n directories from the path of the patches, as mentioned in a answer to a similar question.

It is also possible to run git format-patch --relative <committish> without the --stdout, and it will generate a set of .patch files. These files can then be fed directly to git am with git am --directory blue/red/ path/to/*.patch.


You could create the patch using git diff and then apply it using the patch utility, which allows you to specify the file you want to apply the diff to.

For example:

cd first-repo
git diff HEAD^ -- hello.test > ~/patch_file

cd ../second-repo
patch -p1 blue/red/hi.test ~/patch_file