I had a similar problem not long ago and I solved it using interactive rebasing.
What you do is find the commit hash of the commit before the committed you would like to change. Let say that hash is 376c762c1b28f927595010e98e4ee82d6bc63de3
# first git checkout the correct branch
git rebase -i 376c762c1b28f927595010e98e4ee82d6bc63de3
You then get a list of all the commits after the commit of the commit hash, with a part of the commit message.
pick 376c762 Commit with wrong file
pick e145ef2 Fourth before last commit
pick d969e5b Third before last commit
pick 7b92c09 Second before last commit
pick db1dea3 First before last commit
pick ff120d6 Most recent commit message
# Rebase 621d70a..ff120d6 onto 621d70a (6 commands)
#
# Commands:
# p, pick <commit> = use commit
# r, reword <commit> = use commit, but edit the commit message
# e, edit <commit> = use commit, but stop for amending
# s, squash <commit> = use commit, but meld into previous commit
# f, fixup [-C | -c] <commit> = like "squash" but keep only the previous
# commit's log message, unless -C is used, in which case
# keep only this commit's message; -c is same as -C but
# opens the editor
# x, exec <command> = run command (the rest of the line) using shell
# b, break = stop here (continue rebase later with 'git rebase --continue')
# d, drop <commit> = remove commit
# l, label <label> = label current HEAD with a name
# t, reset <label> = reset HEAD to a label
# m, merge [-C <commit> | -c <commit>] <label> [# <oneline>]
...
What you can do here is change the word before the commit to edit
instead of pick
. In our case:
edit 376c762 Commit with wrong file
Then you save the file and exit, Ctr + X
, Y
and Enter
if you are using nano.
You are then dropped back to the command line just after the commit. You can the do the following to undo the previous commit. The files and you will have the uncommitted changes. The prompt will show the first 7 characters of the commit hash of the commit you are currently in.
git restore HEAD^
Then you can either remove/add/change files from the commit, add and commit the change. To continue the rebase you then do:
get rebase --continue
If the same files are changed in later commits you could get conflicts you have to fix and commit before you can --continue
. When the rebase is complete you will be