Git中跨分支不同目录下文件的变更合并方法咨询
Absolutely! You can map directories to apply changes from folder2 in your source branch to folder4 in your target branch—Git has flexible tools to handle this exact scenario. Here are two reliable methods to get this done:
Method 1: Generate and Modify a Patch File (Best for Multiple Files/Directories)
This approach works great if you have changes across multiple files in the sameFolder directory, or if you want to review the exact changes before applying them.
Check out your target branch first:
git checkout target-branchGenerate a diff patch from your source branch that captures only the changes in the directory you care about:
git diff source-branch -- folder1/folder2/sameFolder/ > directory-changes.patchEdit the patch to map the directory paths—we need to replace all instances of
folder1/folder2/withfolder3/folder4/. You can do this with a text editor, or use a command likesedfor quick batch replacement:# On Linux/macOS sed -i 's/folder1\/folder2\//folder3\/folder4\//g' directory-changes.patch # On Windows (PowerShell) (Get-Content directory-changes.patch) -replace 'folder1/folder2/', 'folder3/folder4/' | Set-Content directory-changes.patchApply the modified patch to your target branch:
git apply directory-changes.patchIf you hit merge conflicts, use the
--rejectflag to apply as much as possible and review the.rejfiles for manual fixes:git apply --reject directory-changes.patchVerify the changes and commit them once you’re satisfied:
git add folder3/folder4/sameFolder/ git commit -m "Apply changes from source-branch's folder2/sameFolder to folder4/sameFolder"
Method 2: Direct Checkout and Move (Best for Single File)
If you only need to apply changes to a single file, this is a quicker shortcut:
Check out the target branch:
git checkout target-branchCheck out the modified file from the source branch:
git checkout source-branch -- folder1/folder2/sameFolder/fileWithChangesMove the file to the target directory path:
mv folder1/folder2/sameFolder/fileWithChanges folder3/folder4/sameFolder/Clean up the old directory structure (if it’s empty) and commit:
rm -rf folder1 git add folder3/folder4/sameFolder/fileWithChanges git commit -m "Update fileWithChanges from source-branch's folder2 to target's folder4"
Pro Tip for Repeated Mapping
If you find yourself needing to do this directory mapping regularly, you can set up a custom merge driver in your .gitattributes file. This lets Git automatically handle the path mapping during merges, but it requires a bit more setup—let me know if you want details on that!
Hope this helps you get those changes mapped over smoothly. If you run into any issues with the commands or patch editing, feel free to ask for clarification.
内容的提问来源于stack exchange,提问作者Sergey

