'How to revert changes from old commit in a single file

How do I revert/remove the changes done in an older multi-file commit, but only do it in a single file? I.e. something like

git revert <commit-specifier> <file>

except git revert does not accept <file> argument. None of the following answers addresses this problem:

Git: Revert old commit on single file is rather about how to debug conflicts.

Undo a particular commit in Git that's been pushed to remote repos does not address my single file issue.

Git: revert on older commit also does not address single file issue.



Solution 1:[1]

You can revert it first:

git revert <commit-specifier>

then reset HEAD~1:

git reset --soft HEAD~1

and git add only the file that you want to do the revert:

git add -- <revert_file>

Now you can commit again

git commit --amend

remove all the other changes:

git checkout -- .

Solution 2:[2]

I accidentally committed a file with a couple of lines of changes and realized after 10 or so commits later. That file should have never been part of any commit. Reverting using any of the suggested answers in this post or any other SO answers was horrible in my case. Ran into lots of merge conflict hell and numerous git errors. I gave up and manually opened the local file and copied/pasted the text from master and made the commit. Viola! PR didn't show that file at all as changed - luckily I'm the only one working on that repo for now. It literally took me 10 seconds. If I followed the answers in SO, I would probably spend 15 or more minutes and introduced more problems trying to fix the conflicts. Why in the world git has to make things super complicated for trivial use cases?! So if you run into issues like I had, see if you can revert the changes directly on the file itself and commit.

I realize what I did may not apply to everyone's situation but still simple things are so unnecessarily complicated in git! Just look at the number of error prone git commands you need to monkey around with to accomplish what I did in 10 seconds.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 lexdo
Solution 2