I know you can merge/cherry-pick changes from a certain commit but is there a way to merge/cherry-pick changes from a commit but only below a certain line in code, e.g.: merge/cherry-pick changes from a commit 25gh4q1 but only below line 202?
-
No you can’t merge part of a file using git. – evolutionxbox Jul 06 '20 at 13:15
-
@evolutionxbox I think I've managed to find an answer although not doing precisely what I was asking, but achieving the same thing. – matzar Jun 24 '21 at 09:31
2 Answers
it's not a one-liner but you could do this:
git cherry-pick 25gh4q1
git reset --mixed HEAD~
git add -p
<interactively stage only relevant parts of the file>
git commit
git reset --hard
explanation:
git cherry-pick 25gh4q1
- cherry pick the whole commit, including the unwanted things
git reset --mixed HEAD~
- keeps the files changed as in commit 25gh4q1
but they will now appear as "Changes not staged for commit"
git add -p
- this allows to interactively stage only some of the changes, not all of them, including parts of files; -p
stands for patch
.
git commit
- commit the staged changes
git reset --hard
- clean up the unwanted parts of commit 25gh4q1
which haven't been staged or committed

- 753
- 6
- 6
git checkout --patch <commit-tag-from-any-branch>
This will enter into a patching mode in witch we'll be able to see the commit divided into hunks (in git chunks of code are called hunks - see In the context of git (and diff), what is a "hunk" for more details) and we'll be presented with options to operate on the hunks of the commit, e.g.: add them to the index, drop, move between hunks and more

- 287
- 2
- 19