Revert a file to a specific version in git

To revert a commit in git you can use the git revert command, this undoes all the changes of the given commit with a new commit. But what if you only want to revert one specific file to a specific revision?

First you need to identify the revision that you are after by using the git log command, you can see the history of a specific file by appending it to the command:

$ git log README.txt
commit 20f4b96db867e471b16b1392af0ffe05f2c5976e (HEAD -> feature-c)
Author: Mark Cornelissen <mark@boxture.com>
Date:   Thu Oct 7 20:03:20 2021 +0200

    Adding even more text, and FILE2

commit 30d3c934363f7effe51ac528cd1ce16dbab2bf57
Author: Mark Cornelissen <mark@boxture.com>
Date:   Thu Oct 7 20:02:28 2021 +0200

    Adding some more text and FILE1

commit d2bcd858aadf352f0fb33fe33249a972e08e3301 (origin/trunk, origin/HEAD, trunk)
Author: Mark Cornelissen <mark@boxture.com>
Date:   Sat Nov 7 08:50:17 2020 +0100

    Initial commit

Then use the git checkout command to get the version that you want to restore:

$ git checkout 30d3c934363f7effe51ac528cd1ce16dbab2bf57 -- README.txt
$ git status
On branch feature-c
Changes to be committed:
  (use "git restore --staged <file>..." to unstage)
        modified:   README.txt

The selected revision is now staged for commit, you can now either make further changes to it or commit it directly.

If you want to try the commands from this article you can get a copy of the repository I used from GitHub (and checkout branch feature-c though).