如何将单个文件的版本从一个 git 分支复制到另一个?

我有两个完全合并在一起的分支。

但是,合并完成后,我意识到一个文件已被合并弄乱了(其他人进行了自动格式化,gah),在另一个分支中更改为新版本会更容易,并且然后将其更改插入分支后重新插入我的一行更改。

那么 git 中最简单的方法是什么?

答案

git checkout otherbranch myfile.txt
git checkout <commit_hash> <relative_path_to_file_or_dir>
git checkout <remote_name>/<branch_name> <file_or_dir>
git show commit_id:path/to/file > path/to/file
git show TREEISH:path/to/file >path/to/local/file
git diff --stat "$branch"
  git checkout --merge "$branch" "$file"
  git diff --stat "$branch"
git checkout sub_branch file_path/my_file.ext
git checkout other-branch app/**
$ git checkout directory/somefile.php feature-B

$ git status
On branch feature-A
Your branch is up-to-date with 'origin/feature-A'.
Changes to be committed:
  (use "git reset HEAD <file>..." to unstage)

        modified:   directory/somefile.php
$ git show feature-B:directory/somefile.php > directory/somefile.php

$ git status
On branch feature-A
Your branch is up-to-date with 'origin/feature-A'.
Changes not staged for commit:
  (use "git add <file>..." to update what will be committed)
  (use "git checkout -- <file>..." to discard changes in working directory)

        modified:   directory/somefile.php

no changes added to commit (use "git add" and/or "git commit -a")