Solution
The magical command which helps in such cases is called git checkout -p files
. As you know, without the -p, git checkout replaces the requested files or directories of the current working tree with those from HEAD (the most recent commit of the currently active branch).
The -p option makes this process interactive. Git will then examine each change in your files and ask what to do. Then you can decide if you want to keep that change, throw it away or something else. The output looks like in the following screenshot:
The relevant pieces of the source code are displayed like in a usual diff. All you need to do know is to decide if you want to keep these changes or throw them away. Important: Note that git asks if you want to discard it, so you have to write n to keep them. It happened a few times to me that I accidently throw away something that I actually wanted to keep.
More options
As you can see, there are many more optiosn to choose from than just keep or throw away. You can get a short help by typing ?, which will display the following
y - discard this hunk from worktree
n - do not discard this hunk from worktree
q - quit; do not discard this hunk nor any of the remaining ones
a - discard this hunk and all later hunks in the file
d - do not discard this hunk nor any of the later hunks in the file
g - select a hunk to go to
/ - search for a hunk matching the given regex
j - leave this hunk undecided, see next undecided hunk
J - leave this hunk undecided, see next hunk
k - leave this hunk undecided, see previous undecided hunk
K - leave this hunk undecided, see previous hunk
s - split the current hunk into smaller hunks
e - manually edit the current hunk
? - print help