How to use git patch system to apply changes into another folder

Problem which needs to be fixed:

Project has two main directories with a lot files. Some of files are almost the same. Some changes to those files should be transfered to other main directory.

Let’s create testing git repository.

(Today I have learned that echo "whatever" > file.txt in PowerShell creates UTF-16 text file which git treats as binary file not text one. Even after creating .gitattributes file)

You should use bash. On Windows git bash ships with git installer.

After this script is doing it’s job, file structure will like this:


Ok, make some changes to main directory.

Now make commit with those changes

    git commit -am "important changes"

Create patch file git format-patch HEAD~. File named 0001-important-changes.patch is created.

Now comes the a magic part. Applying patch on another main directory.

Here is a command

git apply -p3 --directory='left/qwerty/foo'  0001-important-changes.patch

Here is an explanation. First of look how .patch file looks like.

It’s text file with changes to each file, each file have own section which looks like this.


By using arguments to git apply we change how header looks on applying patch.

  • -p3 removes 3 first folder parts from header. Modyfying from a/right/bar/a.txt into a.txt.
  • --directory='left/qwerty/foo' is a prefix added to each header. Modifying from a.txt to left/qwerty/foo/a.txt

Programista, domowy kucharz i "amator amerykańskiej polityki". Zbieram informacje z całej sieci, po odrzuceniu chwastów i dodaniu swojej opinii publikuje na blogu.