'Git: Merge Specific File from Specific Commit

I have one version of a file at commit "#abc123" and the current version of the same file locally.

I want to MERGE, NOT REVERT, the two versions for only this file.

I read about some workarounds using "git cherry pick", but nothing direct.
Is there a simple way of doing this?



Solution 1:[1]

I would:

  • make sure the current version of that file is committed.

  • switch to a new branch from the current commit:

      git switch -c tmp
    
  • restore that one file from the old commit, using git restore:

      git restore -s abc123 -SW -- aFile
      git restore --source=<tree> --staged --worktree -- <pathspec>
    
      git commit -m "restore old version of a file
    

Meaning: restore aFile content from commit abc123 -- the source --, and apply that content both to the index/cache (--staged), and the working tree -- where files are checked out: --worktree)

  • finally I can merge two commits, which will merge only that one file

      git switch main (or master)
      git merge tmp
    

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