Git: Move commits to new branch

Suppose you have a few commits in a git repository, and some of them are on the wrong branch. They're listed below from the oldest (a) to newest (g). The letters represent the commit checksums.

a b c d e f g

You want to move the bold commits b, d, and e to a new branch. So start by checking out the commit before the first bad one and creating a branch there.

git co a
git checkout -b newbranch

This puts you on the new branch starting at a. Now cherry pick the wrong commits into the new branch. This will copy the commits to the new branch.

git cherry-pick b d e

At this point the new and old branches both have commits b, d, and e. Check out the old branch and remove the bad commits from it. I like to use git rebase for this.

git checkout oldbranch
git rebase -i HEAD~7

Change 'pick' to 'delete' for commits b, d, and e. Done!