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

然而,在合并完成后,我意识到一个文件已经被合并弄乱了(别人做了一个自动格式化,啊),在另一个分支中更改到新版本会更容易,然后在把它带入我的分支后重新插入我的一行更改。

Git中最简单的方法是什么呢?


当前回答

请注意,在接受的答案中,第一个选项将从另一个分支中分期整个文件(如git add…已经执行),而第二个选项只会导致复制文件,而不会执行更改(就好像您刚刚手动编辑了文件,并且有突出的差异一样)。

Git从另一个分支复制文件而不登台

阶段性的更改(例如git添加文件名):

$ 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")

其他回答

我在类似的搜索中得到了这个问题。在我的例子中,我希望将一个文件从另一个分支提取到与文件原始位置不同的当前工作目录中。答:

git show TREEISH:path/to/file > path/to/local/file

抱歉,在恢复文件之前没有人提到这个 你真的想预览与该分支相关的局部更改,因此:

git diff <other-branch-name> -- <filename>

然后当你接受一个丢失(覆盖),你可以跟随:

git restore --source <other-branch-name> <filename>
or
git checkout <other-branch-name> <filename>

请注意,在接受的答案中,第一个选项将从另一个分支中分期整个文件(如git add…已经执行),而第二个选项只会导致复制文件,而不会执行更改(就好像您刚刚手动编辑了文件,并且有突出的差异一样)。

Git从另一个分支复制文件而不登台

阶段性的更改(例如git添加文件名):

$ 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")

按照madlep的回答,您还可以使用目录blob从另一个分支复制一个目录。

git checkout other-branch app/**

至于OP的问题,如果你只改变了一个文件在那里,这将工作良好。

使用checkout命令:

  git diff --stat "$branch"
  git checkout --merge "$branch" "$file"
  git diff --stat "$branch"